Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex question: independent position of words

Tags:

regex

is it possible to define a regex pattern which checks eg. for 3 terms independent to their position in the main string?

eg. my string is something like "click here to unsubscribe: http://www.url.com"

the pattern should also work with "http:// unsubscribe click"

thx

like image 693
Fuxi Avatar asked Apr 08 '10 16:04

Fuxi


People also ask

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 the difference between \b and \b in regular expression?

Using regex \B-\B matches - between the word color - coded . Using \b-\b on the other hand matches the - in nine-digit and pass-key .

How do you search for a regex pattern at the beginning of a string?

The meta character “^” matches the beginning of a particular string i.e. it matches the first character of the string. For example, The expression “^\d” matches the string/line starting with a digit. The expression “^[a-z]” matches the string/line starting with a lower case alphabet.


3 Answers

You can use positive lookaheads. For example,

(?=.*click)(?=.*unsubscribe).*http

is a regex that will look ahead from the current position (without moving ahead) for click, then for unsubscribe, then search normally for http.

like image 78
me_and Avatar answered Nov 15 '22 12:11

me_and


It's possible, but results in very complicated regexs, e.g.:

/(click.*unsubscribe|unsubscribe.*click)/

Basically, you would need to have a different regex section for each order. Not ideal. Better to just use multiple regexes, one for each term.

like image 45
tloflin Avatar answered Nov 15 '22 12:11

tloflin


Yes, using conditionals.

http://www.regular-expressions.info/conditional.html

like image 37
jpabluz Avatar answered Nov 15 '22 11:11

jpabluz