简体   繁体   中英

Set length of a special regular expression

I have a problem with some regular expression's length the deal is that this Regex :

^[A-Za-z][A-Za-z0-9]*(?:[_ .][A-Za-z0-9]+)*$

should only accept strings like :

[str][White space or . or _][str][White space or . or _][str]...[str]

[White space or . or _] : should not be repeated in the same sequence.

My question is how can i limit the full string's length to between {6,12} , i tried with :

^[[A-Za-z][A-Za-z0-9]*(?:[_ .][A-Za-z0-9]+)*]{6,12}$

But it didn't work well it causes the repetition of [White space or . or _] beside it allows them to be at the edges of the string.

Best regards.

You can make use of a lookahead for this:

^(?=.{6,12}$)[A-Za-z][A-Za-z0-9]*(?:[_ .][A-Za-z0-9]+)*$
 ^^^^^^^^^^^^

Makes sure the coming match is between 6 to 12 characters long.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM