正则表示式的子模式

使用()表示一个子模式,括号中的内容作为一个整体出现。
(red)+  ==> redred, redredred, 等多个red重复的情况

子模式的扩展语法

Python3正则表达式(4)-LMLPHP

案例1

telNumber = 'Suppose my Phone No. is 0535-1234567, yours is 010-12345678, his is 025-87654321.'
pattern = re.compile(r'(\d{3,4})-(\d{7,8})')
pattern.findall(telNumber)
 
结果:
[('0535', '1234567'), ('010', '12345678'), ('025', '87654321')]

match对象的主要方法

Python3正则表达式(4)-LMLPHP

案例2

m = re.match(r'(\w+) (\w+)', "Hello Bright, Good!")
print('返回整个模式内容:{0}'.format(m.group(0)))
print('返回第一个子模式内容:{0}'.format(m.group(1)))
print('返回第二个子模式内容:{0}'.format(m.group(2)))
print('返回指定的多个子模式内容:{0}'.format(m.group(1, 2)))
结果:
返回整个模式内容:Hello Bright
返回第一个子模式内容:Hello
返回第二个子模式内容:Bright
返回指定的多个子模式内容:('Hello', 'Bright')

案例3

exampleString = """There shoule be one -- and preferably only one -- obvious way to do it.
Althought that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is offten better than right now.""" pattern1 = re.compile(r'(?<=\w\s)never')
matchResult1 = pattern1.search(exampleString)
print('查找句子末尾的单词在整个字符串中跨度:{0}'.format(matchResult1.span())) pattern2 = re.compile(r'(?:is\s)better(\sthan)')
matchResult2 = pattern2.search(exampleString)
print('查找句子末尾的单词在整个字符串中跨度:{0}'.format(matchResult2.span()))
print('查找整个模式:{0}'.format(matchResult2.group(0)))
print('查找第一个字模式:{0}'.format(matchResult2.group(1)))
结果:
查找句子末尾的单词在整个字符串中跨度:(160, 165)
查找句子末尾的单词在整个字符串中跨度:(145, 159)
查找整个模式:is better than
查找第一个字模式: than

案例4

m = re.match(r"(?P<first_name>\w+) (?P<last_name>\w+)", 'Malcolm Reynolds')
print('使用子模式名字打印第1个:{0}'.format(m.group('first_name')))
print('使用子模式名字打印第2个:{0}'.format(m.group('last_name')))
结果
使用子模式名字打印第1个:Malcolm
使用子模式名字打印第2个:Reynolds

案例5

m = re.match(r'(\d+)\.(\d+)', "24.1456")
m.groups()
结果
('24', '1456')

案例6

m = re.match(r"(?P<first_name>\w+) (?P<last_name>\w+)", 'Malcolm Reynolds')
m.groupdict()
结果
{'first_name': 'Malcolm', 'last_name': 'Reynolds'}

案例7

exampleString = """There shoule be one -- and preferably only one -- obvious way to do it.
Althought that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is offten better than right now."""
pattern = re.compile(r'(?<=\w\s)never(?=\s\w)') # 查找不在句子开头和结尾的never
matchResult = pattern.search(exampleString)
matchResult.span()
结果
(176, 181)

案例8

Python3正则表达式(4)-LMLPHP
 
 
 
 
05-11 22:18