Home > Backend Development > C++ > How to Limit the Length of Characters in a Regular Expression?

How to Limit the Length of Characters in a Regular Expression?

DDD
Release: 2025-01-26 20:14:15
Original
890 people have browsed it

How to Limit the Length of Characters in a Regular Expression?

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>
Copy after login

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>
Copy after login

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>
Copy after login

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:

    The
  • [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.
  • Positive lookahead assertion (?=.{1,15}$) Use the $ anchor to assert that a specified number of characters must be at the end of a string.
  • This method works with ECMAScript and other regular expression flavors, such as Python. However, in Python you need to use 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>
Copy after login

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template