import re
p = re.compile('ab*')
p = re.compile('ab*', re.IGNORECASE) #该参数可以忽略匹配字符串的大小写
r'\n' #代表‘\’和‘n‘
r'\\section' #代表‘\section‘ ??
import re
p = re.compile('[a-z]+')
m = p.match('')
print m
None
<_sre.SRE_Match object; span=(0, 3), match='3b2'>
import re
p = re.compile('[a-z]+')
m = p.match('ok')
m.group() #返回匹配正则表达式的字符串
'ok'
m.start(),m.end() #前者返回匹配字符串开始的位置,后者返回匹配字符串结束的位置
(0, 2)
m.span() #返回一个包括开始和结束位置的元组
(0, 2)
ASCII, A #使\w,\b,\W,\B,\s,\S只匹配ASCII字符,而不匹配Unicode
DOTALL, S #使字符'.'匹配任意字符,包括换行符
INGORECASE, I #使匹配对大小不敏感
LOCALE, L #做本地化识别 ??
MULTILINE, M #多行匹配,会影响 ??
VERBOSE, V #能够使用正则表达式的verbose装填,使之更加清晰易懂 ??
import re
m = re.match('([abc])+','abc')
m.groups()
('c',)
m = re.match('(?:[abc])+','abc')
m.groups()
()
import re
p = re.compile(r'(?P<word>\b\w+\b)')
m = p.search('((Hello World))')
m.group('word')
'Hello'
m.group(1)
'Hello'
#接上
p = re.compile(r'(?P<word>\b\w+)\s+(?P<word>)')
n = p.search('Say Hello')
m.group()
import re
p = re.compile('re(?gular)')
m = p.match('regular expression')
're'
p = re.compile('re(?Gular)')
m = p.match('regular expression')
None
import re
p = re.compile('re(?gular)')
m = p.match('regular expression')
None
p = re.compile('re(?Gular)')
m = p.match('regular expression')
're'
import re
p = re.compile(r'\W+')
p.split('This is a test string of split().')
['This', 'is', 'a', 'test', 'string', 'of', 'split', '']
p.split('This is a test string of split().', 3)
['This', 'is', 'a', 'test string of split().']
import re
p = re.compile(r'(\W+)')
p.split('This is a test string of split().')
['This', ' ', 'is', ' ', 'a', ' ', 'test', ' ', 'string', ' ', 'of', ' ', 'split', '().', '']
import re
re.split('[\W]+','This is a test string of split().')
['This', 'is', 'a', 'test', 'string', 'of', 'split', '']
re.split('([\W]+)','This is a test string of split().')
['This', ' ', 'is', ' ', 'a', ' ', 'test', ' ', 'string', ' ', 'of', ' ', 'split', '().', '']
re.split('[\W]+','This is a test string of split().',3)
['This', 'is', 'a', 'test string of split().']
import re
p = re.compile('(blue|white|red)')
p.sub('color','blue socks and red shoes')
'color socks and color shoes'
p.sub('color','blue socks and red shoes',count = 1)
'color socks and red shoes'
import re
p = re.compile('(blue|white|red)')
p.subn('color','blue socks and red shoes')
('color socks and color shoes', 2)
p.sub('color','no color at all')
('no colors at all', 0)
import re
p = re.compile('x*')
p.sub('-','abxd')
'-a-b-d-'
import re
p = re.compile(r'\d+')
print (re.findall(p,'one1two2three3four4'))
['1','2','3','4']
import re
p = re.compile(r'\d+')
for item in re.finditer(p,'one1two2three3four4'):
print (item.group())
1 2 3 4