开发者

AND operator in regular expression?

开发者 https://www.devze.com 2023-01-20 17:26 出处:网络
Given a st开发者_StackOverflowring, how do I express that a pattern must match multiple regex using the AND operator? For example, I want a password to be a minimum of 5 characters AND maximum of 12 c

Given a st开发者_StackOverflowring, how do I express that a pattern must match multiple regex using the AND operator? For example, I want a password to be a minimum of 5 characters AND maximum of 12 characters.

  • Regex for mimimum 5 characters: .{5,}
  • Regex for maximum 12 characters: .{12}

I know I can combine the above two to something like this: .{5,12}, but this is not what I am trying to achieve. I want to "and" the two regexes.


Well 99% of the time, you would either want to combine them in the parent language, eg.

if (Regex.Match(input,pattern1) && Regex.Match(input,pattern2))
{
   //do work
}

or improve the regex to combine them, eg.

.{5,12}

If you really want to combine within a single regex, you can use look ahead assertions, something like this, but the actual matched value will not be what you might expect.

^(?=.{5,})(?=.{0,12})


The two source regexes are wrong. Anyways, you want .{5,12}.


There is no simple way to do this within the regexes themselves. The algorithms for regex intersection that I know require that you first convert the regex to an automaton.

In your case, the best solution would probably be to create an AndRegex class which combines two regexes.


If you want to check multiple pattern on a string, you can use a look-around :

/^(?=.{5}).{0,12}$/

This way you check that your string is at least 5 chars, and is also at most 12 chars.

But as you said, in this case it's better to combine the two of them in .{5,12}.


If you just want to match min of 5 chars and max of 12, why even bother with regex? You can just use whatever functions your language supports for counting number of characters in a string. Eg Python using len()

>>> s="mypassword"
>>> if len(s) >=5 and len(s) <=12 :
...   print s
...
mypassword

With Ruby

>> s="mypassword"
=> "mypassword"
>> s.size >= 5 and s.size<=12
=> true
0

精彩评论

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

关注公众号