Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

python regular expressions

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
Source by codefreelance.net #
 
PREVIOUS NEXT
Tagged: #python #regular #expressions
ADD COMMENT
Topic
Name
5+6 =