Improvement method of regular expression character length limit
Your original regular expression did not place a limit on character length:
<code>var test = /^(a-z|A-Z|0-9)*[^$%^&*;:,<>?()\""\']*$/</code>
In order to limit the character length to 15, you try to modify the expression as:
<code>var test = /^(a-z|A-Z|0-9)*[^$%^&*;:,<>?()\""\']*${1,15}/</code>
This will throw an error because quantifiers cannot be applied directly to anchors. The correct way to limit the length of an input string is to use a lookahead assertion at the beginning:
<code>^(?=.{1,15}$)[a-zA-Z0-9]*[^$%^&*;:,<>?()\"']*$</code>
This lookahead assertion ensures that the input string matches the specified character range and is between 1 and 15 characters in length, effectively enforcing the character length limit.
Compared to using a restrictive quantifier at the end (like {1,15}), the lookahead approach allows you to limit the length of the entire input string. The quantifier is applied to the subpattern of the lookahead assertion, ensuring that it matches the required number of characters from the beginning of the string.
Here are a few other points to note:
[a-zA-Z0-9]*
subpattern matches a sequence of letters or numbers of any length. It is equivalent to the (a-z|A-Z|0-9)*
subpattern used in your original expression. (?=.{1,15}$)
Use the $
anchor to assert that a specified number of characters must be at the end of a string. A
and Z
anchors instead of ^
and $
. Additionally, if your input string may contain newlines, you can use the [sS]
portable arbitrary character regular expression construct:
<code>^(?=[\s\S]{1,15}$)[a-zA-Z0-9]*[^$%^&*;:,<>?()\"']*$</code>
This ensures that newlines are also included in the character length limit.
The above is the detailed content of How to Limit the Length of Characters in a Regular Expression?. For more information, please follow other related articles on the PHP Chinese website!