In [1]:
import re
Replace the string "foo" when it's got non-words or line boundaries to the left and to the right
In [2]:
re.sub(r'(?:\W|^)foo(?:\W|$)',' FOO ','foo bar foo foofoo barfoobar foo')
Out[2]:
In [3]:
# contains
re.search('\d{3}','foo 123 bar')
Out[3]:
In [4]:
# doesn't contain
re.search('\d{3}','foo 1 23 bar')
In [20]:
# letter 'b' followed by two characters or numbers
pattern = r'b\w{2}'
match = re.search(pattern,"foo bar baz quux")
match
Out[20]:
In [21]:
match.group(0)
Out[21]:
In [6]:
pattern = r'b\w{2}'
re.findall(pattern,'foo bar baz quux')
Out[6]:
In [7]:
re.split('[\s,]+','foo,bar bar quux')
Out[7]:
In [39]:
re.split(r'\b','foo,bar bar-quux')
In [40]:
# only word characters
re.findall(r'\w+','foo,bar bar-quux')
Out[40]:
In [42]:
re.findall(r'\w+|[^\w\s]+','foo,bar bar-quux')
Out[42]:
In [8]:
pattern = "(?<=foo)bar"
replacement = "BAR"
string = "foo bar foobar"
re.sub(pattern,replacement,string)
Out[8]:
In [9]:
pattern = "(?<!foo)bar"
replacement = "BAR"
string = "foo bar foobar"
re.sub(pattern,replacement,string)
Out[9]:
In [10]:
pattern = "foo(?=bar)"
replacement = "FOO"
string = "foo bar foobar"
re.sub(pattern,replacement,string)
Out[10]:
In [11]:
pattern = "foo(?!bar)"
replacement = "FOO"
string = "foo bar foobar"
re.sub(pattern,replacement,string)
Out[11]:
In [12]:
re.match('abc','xx abc xx')
In [13]:
re.match('abc','abc')
Out[13]:
In [14]:
match = re.search('abc','xx abc xx')
match
Out[14]:
In [15]:
match = re.search('abc','xx abc xx abc')
match
Out[15]:
In [16]:
re.fullmatch('foo\d+','foo123')
Out[16]:
In [17]:
re.fullmatch('foo\d+','foo123bar')
In [18]:
re.match('^foo\d+$','foo123')
Out[18]:
In [19]:
re.match('^foo\d+$','foo123bar')
In [ ]:
In [ ]:
In [ ]: