Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python regular expressions OR

Tags:

python

regex

Suppose I want a regular expression that matches both "Sent from my iPhone" and "Sent from my iPod". How do I write such an expression?

I tried things like:

re.compile("Sent from my [iPhone]|[iPod]")  

but doesn't seem to work.

like image 734
Henley Avatar asked Dec 22 '11 20:12

Henley


People also ask

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 .

Can you use or in regex?

Alternation is the term in regular expression that is actually a simple “OR”. In a regular expression it is denoted with a vertical line character | . For instance, we need to find programming languages: HTML, PHP, Java or JavaScript.

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.


2 Answers

re.compile("Sent from my (iPhone|iPod)") 
like image 153
Paul Avatar answered Oct 14 '22 04:10

Paul


re.compile("Sent from my (?:iPhone|iPod)") 

If you need to capture matches, remove the ?:.

Fyi, your regex didn't work because you are testing for one character out of i,P,h,o,n,e or one character out of i,P,o,d..

like image 24
ThiefMaster Avatar answered Oct 14 '22 04:10

ThiefMaster