Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a regex to match a string that contains A but does not contain B

My problem is that i want to check the browserstring with pure regex.

Mozilla/5.0 (Linux; U; Android 3.0; en-us; Xoom Build/HRI39) AppleWebKit/534.13 (KHTML, like Gecko) Version/4.0 Safari/534.13 

-> should match

Mozilla/5.0 (Linux; U; Android 2.2.1; en-us; Nexus One Build/FRG83) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1  

should not match

my tried solution is: /?((?<=Android)(?:[^])*?(?=Mobile))/i but it matches exactly wrong.

like image 747
user1061688 Avatar asked Nov 23 '11 10:11

user1061688


People also ask

How do you say does not contain in regex?

In order to match a line that does not contain something, use negative lookahead (described in Recipe 2.16). Notice that in this regular expression, a negative lookahead and a dot are repeated together using a noncapturing group.

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string). Both are called anchors and ensure that the entire string is matched instead of just a substring.

What is difference [] and () in regex?

[] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9. (a-z0-9) -- Explicit capture of a-z0-9 .


1 Answers

You use look ahead assertions to check if a string contains a word or not.

If you want to assure that the string contains "Android" at some place you can do it like this:

^(?=.*Android).* 

You can also combine them, to ensure that it contains "Android" at some place AND "Mobile" at some place:

^(?=.*Android)(?=.*Mobile).* 

If you want to ensure that a certain word is NOT in the string, use the negative look ahead:

^(?=.*Android)(?!.*Mobile).* 

This would require the word "Android to be in the string and the word "Mobile" is not allowed in the string. The .* part matches then the complete string/row when the assertions at the beginning are true.

See it here on Regexr

like image 162
stema Avatar answered Sep 20 '22 18:09

stema