Home > Web Front-end > JS Tutorial > How to Properly Include a Hyphen in a Regex Character Class?

How to Properly Include a Hyphen in a Regex Character Class?

Linda Hamilton
Release: 2024-11-28 10:22:10
Original
342 people have browsed it

How to Properly Include a Hyphen in a Regex Character Class?

How to Include a Hyphen in a Character Bracket with Regex

When using a character bracket in a regular expression, you may encounter difficulties in including hyphens. The following question illustrates this issue:

In a JavaScript validator, when using the following regex:

$.validator.addMethod('AZ09_', function (value) {
    return /^[a-zA-Z0-9.-_]+$/.test(value);
}, 'Only letters, numbers, and _-. are allowed');

Trying to match a value like "test-123" still triggers an error as if the hyphen is invalid, despite attempting to escape it with \-.
Copy after login

The response to this issue is to place the hyphen at the beginning or end of the character bracket. This modification ensures that it is successfully included in the allowed characters:

/^[a-zA-Z0-9._-]+$/
Copy after login

By making this adjustment, hyphens are now recognized as valid characters within the regex.

The above is the detailed content of How to Properly Include a Hyphen in a Regex Character Class?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template