Regular Expression
import re
re.search
The most common method is match = re.search(pat, str)
. But sometimes we can not find the desired string, and a if statement
is necessary to handle this case.
str = 'an example word:cat!!'
match = re.search(r'word:\w\w\w', str)
if match:
print 'found', match.group() ## 'found word:cat'
else:
print 'did not find'
found word:cat
# re.search return a match object, which contains lots of info
print type(match)
<type '_sre.SRE_Match'>
print match.string # source string
print match.group()
print match.start() # position of w
print match.end() # position of t
print match.endpos # position of last !
print match.span()
an example word:cat!!
word:cat
11
19
21
(11, 19)
re.match
re.match()
and re.search()
are pretty the same. The only difference is that re.match()
match from the very beginning. You can think re.match()
post a ^
restriction on re.search()
.
s = 'python tuts'
match = re.match(r'py',s)
if match:
print(match.group())
s = 'python tuts'
match = re.search(r'^py',s)
if match:
print(match.group())
Syntax
- Chars like
a, X, 9
match itselves; meta char don’t, like. ^ $ * + ? { }[ ] \ | ( )
.
period, match any chars, excluding ‘\n’\w
‘word’, [a-zA-Z0-9]\W
Non - ‘word’\b
match boundary between ‘word’ and ‘non-word’\s
match a single whitespace\S
match non-whitespace\t, \n, \r
match tab, newline, return\d
match [0-9]^
start$
end
Repeat
- ‘+’: one or more
- ‘*’: zero or more
- ‘?’: zero or one
[]
: like ‘or’, indicate a set of chars, so [abc] matches ‘a’ or ‘b’ or ‘c’.
match = re.search(r'[\w.-]+@[\w.-]+',string)
if match:
print match.group()
Group Extraction
圆括号()
有时候需要提取匹配字符的一部分,比如刚才的邮箱,我们可能需要其中的username
和hostname
,这时候可以用()
分别把username
和hostname
包起来,就像r'([\w.-]+)@([\w.-]+)'
,如果匹配成功,那么pattern不改变,只是可以用match.group(1)
和match.group(2)
来username
和hostname
,match.group()
结果不变。
string = 'purple alice-b@google.com monkey dishwasher'
match = re.search(r'([\w\.-]+)@([\w\.-]+)',string)
if match:
# Return subgroup(s) of the match by indices or names.
print match.group() # or match.group(0)
print match.group(1)
print match.group(2)
if match:
# Return a tuple containing all the subgroups of the match, from 1.
print match.groups()
alice-b@google.com
alice-b
google.com
('alice-b', 'google.com')
findall
and groups
()
和findall()
结合,如果包括一或多个group
,就返回a list of tuples
。
str = 'purple alice@google.com, blah monkey bob@abc.com blah dishwasher'
tuples = re.findall(r'([\w\.-]+)@([\w\.-]+)', str)
print tuples # [('alice', 'google.com'), ('bob', 'abc.com')]
for tuple in tuples:
print tuple[0] # username
print tuple[1] # host
[('alice', 'google.com'), ('bob', 'abc.com')]
alice
google.com
bob
abc.com
给re.search
加^
之后是一样的。
re.sub
re.sub(pat, replacement, str)
在str里寻找和pattern匹配的字符串,然后用replacement替换。replacement
可以包含\1
或者\2
来代替相应的group
,然后实现局部替换。
# replace hostname
str = 'alice@google.com, and bob@abc.com'
#returns new string with all replacements,
# \1 is group(1), \2 group(2) in the replacement
print re.sub(r'([\w\.-]+)@([\w\.-]+)', r'\1@yo-yo-dyne.com', str)
alice@yo-yo-dyne.com, and bob@yo-yo-dyne.com