tags:

views:

82

answers:

5

Given a string, 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.

+1  A: 

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

Ignacio Vazquez-Abrams
Oops, you are right. Will edit.
StackOverflowNewbie
+1  A: 

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}.

Colin Hebert
At first I thought that you should do {0, 7} for the second part, but you answer is correct. +1
Max
+3  A: 

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})
Paul Creasey
@Paul, your second regex matches also strings with more than 12 chars.
Colin Hebert
@colin, yes, but that is a flaw in the original regex, not the combination of them! `^.{,12}$` would work of course.
Paul Creasey
@Paul, and the second part of the regex is invalid. `{,12}` isn't useable.
Colin Hebert
+1  A: 

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.

Thom Smith
A: 

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
ghostdog74