昨天,今天,明天,每天的每天,你是否都多懂得一点点...

星期二, 四月 01, 2014

Regex "And" operation

Regex "Or" operation is obvious.

This is a example

^abc$|^123$

This will match abc or 123. 

But how do you do a regex "and"

You may write something like this:

^abc$&^123$

Wrong, this is totally wrong. There is not "&" operator in regex.

Is it possible to do an "And" operation in regex? 

The answer is "YES".

That leads us to the power regex look around feature. 

For "And" operation, what we need is the positive look ahead.

(?m)^(?=.*[A-Z].*)(?=.*[a-z].*)(?=.*?[0-9].*)[^1]*$

Have a look example above. 

Look head matches, but doesn't take space, That means, the regex after the look ahead will start matching from the beginning as well.

In this example, the only matched string will be Abcd5234. 


Abcd1234
ABCD1234
abcd1234
abcdabcd
aBcd1234
aBcdabcd
Abcd5234


Why?

Because this string must match ^(?=.*[A-Z].*), means at least 1 Capital letter. 
Also, it must match (?=.*[a-z].*), one lowercase letter. 
Also, it must match (?=.*?[0-9].*), one number
and lastly, it must match [^1]*, no "1" included.





--
Feng

没有评论:

其它博客地址

此博客的同步博客地址: http://fengnz.wordpress.com
这里进入我的MSN SPACE.