Python - Regular Expressions - Code
Python - Regular Expressions - Code
----------------------------------------------------
[] A set of characters
-------------------------
import re
#Find all lower case characters alphabetically between "a" and "m":
x = re.findall("[a-m]", str)
print(x)
------------------------
\ Signals a special sequence
------------------------------
import re
x = re.findall("\d", str)
print(x)
-------------------------
. Any character (except newline character)
----------------------------------------
import re
#Search for a sequence that starts with "he", followed by two (any) characters, and an "o":
x = re.findall("he..o", str)
print(x)
-----------------------
^ Starts with
-----------------
import re
x = re.findall("^hello", str)
if (x):
print("Yes, the string starts with 'hello'")
else:
print("No match")
---------------------------
$ Ends with
-------------
import re
x = re.findall("world$", str)
if (x):
print("Yes, the string ends with 'world'")
else:
print("No match")
----------------------------
* Zero or more occurrences
----------------------------
import re
str = "The rain in Spain falls mainly in the plain!"
x = re.findall("aip*", str)
print(x)
if (x):
print("Yes, there is at least one match!")
else:
print("No match")
-----------------------------------------
+ One or more occurrences
----------------------------------
import re
x = re.findall("aip+", str)
print(x)
if (x):
print("Yes, there is at least one match!")
else:
print("No match")
-------------------------------------------------
{} Exactly the specified number of occurrences
--------------------------------------------------
import re
#Check if the string contains "a" followed by exactly two "l" characters:
x = re.findall("al{2}", str)
print(x)
if (x):
print("Yes, there is at least one match!")
else:
print("No match")
-----------------------------------------------
| Either or
-------------------
import re
x = re.findall("falls|stays", str)
print(x)
if (x):
print("Yes, there is at least one match!")
else:
print("No match")
-----------------------------
-------------------