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 \-.
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._-]+$/
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!