Home >Web Front-end >JS Tutorial >How to Restrict Character Length in Regular Expressions?

How to Restrict Character Length in Regular Expressions?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-17 03:38:03393browse

How to Restrict Character Length in Regular Expressions?

Restricting Character Length in Regular Expressions

When using regular expressions to validate input, it may be necessary to limit the length of characters in the match. This can be achieved using anchors and zero-width assertions.

The example provided in the question uses a regular expression to match strings containing only letters, numbers, and certain special characters, with no character length restriction. However, when attempting to restrict the length to 15 characters using the quantifier {1,15}, a syntax error is encountered.

The reason for this is that quantifiers cannot be applied to anchors. To restrict the character length, an alternative approach is to use a lookahead anchored at the beginning of the string.

The modified expression:

^(?=.{1,15}$)[a-zA-Z0-9]*[^$%^&amp;*;:,<>?()"]*$

This expression includes a lookahead, (?=.{1,15}$), which checks for a sequence of 1 to 15 characters at the end of the string. The main part of the expression compares the length of the input string.

Similarly, expressions can be crafted for various programming languages:

Flavor Expression
ECMAScript, C ^(?=.{1,15}$)[a-zA-Z0-9]*[^$%^&amp;*;:,<>?()"]*$
Other regex flavors, Python A(?=.{1,15}z)[a-zA-Z0-9]*[^$%^&*;:,<>?()"]*z

Additional Considerations

  • Use [a-zA-Z0-9] instead of (a-z|A-Z|0-9) for efficiency.
  • To allow for newlines in the input, replace {1,15} with [sS]{1,15}.

The above is the detailed content of How to Restrict Character Length in Regular Expressions?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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