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

How to Restrict Character Length in a Regular Expression?

Barbara Streisand
Release: 2024-11-20 03:17:02
Original
931 people have browsed it

How to Restrict Character Length in a Regular Expression?

Restricting Character Length in a Regular Expression

When using regular expressions to match particular patterns in strings, it is often necessary to restrict the character length to ensure accurate matching. In the provided example:

var test =  /^(a-z|A-Z|0-9)*[^$%^&*;:,<>()?""']*$/
Copy after login

This regex matches any string consisting of letters or digits without any restricted character length. An attempt to restrict the character length to 15 using [^$%^&*;:,<>()?""']*${1,15} results in an error.

To resolve this issue and enforce a character limit, use a lookahead anchored at the beginning of the string:

^(?=.{1,15}$)...
Copy after login

This lookahead checks if the string matches 1 to 15 characters but excludes the newline at the end (due to $). It restricts the length of the entire input string.

Using a quantifier at the end, such as [^$%^&*;:,<>()?""']{1,15}, will only restrict the length of the second character class, not the whole string.

For strings that may contain a newline sequence, use [sS] to match any character:

^(?=.[\s\S]{1,15}$)...
Copy after login

This ensures that the character length restriction applies across the entire string, regardless of newlines.

The above is the detailed content of How to Restrict Character Length 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template