开发者

overall matching

开发者 https://www.devze.com 2023-03-13 07:01 出处:网络
to search a single char in RegEx is easy. exp: at least one digit: \\d so i need to match at least 2 digit in the text

to search a single char in RegEx is easy.

exp: at least one digit:

\d

so i need to match at least 2 digit in the text

.*\d{2}.* or .*\d\d.* #### "d2dr5" -> not match... d22r or d00r match..

will not work because RegEx engine look for these numbers as consecutive how can I search for overall? for example

I want to match at least 3 digit and 2 uppercase word in the text. and the text length can be max 12. how can I do this ? If you can give an explained example so then i may have a point to re-search

example match:

a9r2lDpDf2 - matches. at开发者_开发知识库 least 3 digit 2 upper case and not exceeding 12 char in total.


If you want to make sure there is only three digits in the string you can try this (add start and end of string if needed):

[^\d]*\d[^\d]*\d[^\d]*\d[^\d]*

[^\d]* - anything except digits.

Same pattern can be used to check for uppercase letters:

[^A-Z]*[A-Z][^A-Z]*[A-Z][^A-Z]*

RegEx is not the best tool to check length. The language you use has something like length(str) or str.length or str.length() etc.

It can be done with lookahead feature. This is how RegEx looks in Perl (and it does what you ask):

/^(?=.*\d.*\d.*\d)(?=.*[A-Z].*[A-Z]).{12}$/

(?=.*\d.*\d.*\d) - "looks ahead" to see if there are 3 digits

(?=.*[A-Z].*[A-Z]) - "looks ahead" to see if there are 2 uppercase letters

.{12} - length must be precisely 12 characters. Any character 12 times.


I dont think regexes are the optimal solution here , but for academic interest

(?=(.*[0-9]){3})(?=(.*[A-Z]){2}).{5,12}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号