python regular expressions

40

import re

# returns a match object if found else None
txt = "Hello world"
x = re.search(r"[a-zA-z]+", txt)

if x:
    print("YES! We have a match!", x)
else:
    print("No match")
# output YES! We have a match! <re.Match object; span=(0, 5), match='Hello'>


# returns a list of all matches found - regular express finds all vowels in this example
txt = "This is a test"
x = re.findall(r"[aeiou]", txt)
print(x)
# output ['i', 'i', 'a', 'e']


# returns a list of all matches found - regular expression find is or test in string case-insensitive
txt = "This iS a Test"
x = re.findall("(is|test)", txt, flags=re.IGNORECASE)
print(x)
# output ['is', 'iS', 'Test']

txt = "This is a silly string"
# splits a string into a list using regular expression
x = re.split(r"silly", txt)
print(x)
# output ['This is a ', ' string']


# replace concatenated tototo with to
txt = "We need tototo run "
x = re.sub(r"(to)+", "to", txt)
print(x)
# output We need to run
import re
>>> m = re.search('(?<=abc)def', 'abcdef')
>>> m.group(0)
'def'
>>> pattern = re.compile("o")
>>> pattern.match("dog")      # No match as "o" is not at the start of "dog".
>>> pattern.match("dog", 1)   # Match as "o" is the 2nd character of "dog".
<re.Match object; span=(1, 2), match='o'>

Comments

Submit
0 Comments