简体   繁体   中英

Using RegEx to Count the Length of the String in a Matched Pattern

I've been trying to resolve this all day.

Here are the requirements:
- I want to match strings that optionally starts with " _ "
- Should then continue with one or more case-insensitive alphabet
- Should then contain an optional " _ " or " - " followed by case-insensitive alphanumeric characters (This step should match at lease once).
- Then it may optionally end with " _ "

The above requirements are not a problem 'cos I achieved that with:

/_?[A-Za-z]([-_]?[A-Za-z0-9])+_?/

The above RegEx matches:

  • user_
  • usEr-nAme
  • uSer_naMe-Two_
  • _Userna-Me_tHree-and-four

THE PROBLEM
How do I make it match only 6 to 25 characters?

I Tried

/(_?[A-Za-z]([-_]?[A-Za-z0-9])+_?){6,25}/

but it still matches string less than 6 like Use-r

Put a lookahead assertion at the start:

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

Demo here .

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