View Category

Check if a string matches a regular expression

Display "ok" if "Hello" matches /[A-Z][a-z]+/
python
found = re.match(r'[A-Z][a-z]+', 'Hello')
if found:
print 'ok'

Check if a string matches with groups

Display "two" if "one two three" matches /one (.*) three/
python
match = re.match(r'one (.*) three', 'one two three')
if match:
print match.group(1)

Check if a string contains a match to a regular expression

Display "ok" if "abc 123 @#$" matches /\d+/
python
found = re.search(r'\d+', 'abc 123 @#$')
if found:
print 'ok'

Loop through a string matching a regex and performing an action for each match

Create a list [fish1,cow3,boat4] when matching "(fish):1 sausage (cow):3 tree (boat):4" with regex /\((\w+)\):(\d+)/
python
map(''.join, re.findall(r"\((\w+)\):(\d+)", "(fish):1 sausage (cow):3 tree (boat):4"))
--------------------------------------------------------------------------
(''.join(m.groups()) for m in re.finditer(r"\((\w+)\):(\d+)", "(fish):1 sausage (cow):3 tree (boat):4"))

Replace the first regex match in a string with a static string

Transform "Red Green Blue" into "R*d Green Blue" by replacing /e/ with "*"
python
print re.sub(r'e', '*', 'Red Green Blue', 1)

Replace all regex matches in a string with a static string

Transform "She sells sea shells" into "She X X shells" by replacing /se\w+/ with "X"
python
transformed = re.sub(r'se\w+', 'X', 'She sells sea shells')

Replace all regex matches in a string with a dynamic string

Transform "The {Quick} Brown {Fox}" into "The kciuQ Brown xoF" by reversing words in braces using the regex /\{(\w+)\}/.
python
transformed = re.sub(r'\{(\w+)\}',
lambda match: match.group(1)[::-1],
'The {Quick} Brown {Fox}')