简体   繁体   中英

Regex pattern to match limited length

I have some data that is formed from characters and digits in any random order. The one thing is for sure that it must contain both digits and characters together. I have made a regex that matches this case. I now would like to go a bit further and limit it to strings with 5 symbols only.

'1aa21' -match '(\d+)+[a-z]|[a-z]+(\d+)'

I have tried to add {5} at the end and \\S{5} too and so on. It does not seem to work. Whats the best way to reach the desired?

We can use two lookaheads at start of the string. One to check for the fixed length of 5 characters and one to check for at least one digit. The letter can be matched inside the pattern.

^(?=\S{5}$)(?=\D*\d)\d*[a-z][a-z\d]*$
  • (?=\\S{5}$) looks ahead for $ end after 5 non-whitespace characters
  • (?=\\D*\\d) looks ahead for a digit after any amount of non-digits
  • \\d*[az][az\\d]* matches any amount of digits, followed by a letter and any alnum

See this demo at regexstorm . For caseless matching add the (?i) flag .

There are different options how to combine the lookaheads and what to match. Another one would be to check for the digit and alpha by use of the lookaheads and match 5 alphanumeric characters.

^(?=\D*\d)(?=\d*[a-z])[a-z\d]{5}$

Or using one negative lookahead with alternation.

^(?!\d*$|[a-z]*$)[a-z\d]{5}$

Depending on the input which one would be of best performance.

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