re.match()方法:
尝试从字符串的起始位置匹配正则表达式,如果匹配成功,就返回一个匹配成功的结果;如果匹配失败,则返回None。
re.match(pattern, string, flags=0)
- pattern : 正则中的模式字符串。
- string : 要被查找替换的原始字符串。
- flags : 标志位,用于控制正则表达式的匹配方式,如:是否区分大小写,多行匹配等等。
例1:
import re
content = 'Hello 123456789 Word_This is just a test'
result = re.match('^Hello\s\d{9}.*test$', content)
# ^标识开头,这里匹配以Hello开头的字符串
# $标识结尾,这里匹配以test结尾的字符串
# \s 匹配空白字符串
# \d{9} 匹配9位数字
# .匹配除了换行符之外的任意字符,*匹配零次或多次,二者结合起来能够匹配任意字符(除换行符)
print(result)
print(result.group()) # group()方法输出匹配到的内容
print(result.span()) #span()方法输出匹配的范围
结果:可以看到匹配成功,打印出匹配的字符串
<_sre.SRE_Match object; span=(0, 40), match='Hello 123456789 Word_This is just a test'>
Hello 123456789 Word_This is just a test
(0, 40)
Process finished with exit code 0
例2:没有结尾标识符$的情况下
import re
content = 'Hello 123456789 Word_This is just a test'
result = re.match('^Hello\s\d{9}.*just', content)
print(result)
print(result.group())
print(result.span())
结果:匹配到just结束
<_sre.SRE_Match object; span=(0, 33), match='Hello 123456789 Word_This is just'>
Hello 123456789 Word_This is just
(0, 33)
Process finished with exit code 0
例3:将例2中的just改为s
import re
content = 'Hello 123456789 Word_This is just a test'
result = re.match('^Hello\s\d{9}.*s', content)
print(result)
print(result.group())
print(result.span())
结果:
<_sre.SRE_Match object; span=(0, 39), match='Hello 123456789 Word_This is just a tes'>
Hello 123456789 Word_This is just a tes
(0, 39)
Process finished with exit code 0
可以发现,最终输出的结果是到 tes
这就是默认的贪婪模式,因为在9个数字后面有 This 中的 s,is 中的s,test中的s,贪婪模式会尽可能多的匹配字符,在这里匹配到了最远的 test 中的 s。
将贪婪模式变为非贪婪模式,只需将 .* 后面加个?, 变为 .*?即可。
例4:将例3中的 .* 变为 .*?
import re
content = 'Hello 123456789 Word_This is just a test'
result = re.match('^Hello\s\d{9}.*?s', content)
print(result)
print(result.group())
print(result.span())
结果:
<_sre.SRE_Match object; span=(0, 25), match='Hello 123456789 Word_This'>
Hello 123456789 Word_This
(0, 25)
Process finished with exit code 0
可以看到匹配出来的字符串中的 s 只匹配到了 This 中的 s,这就是非贪婪模式,尽可能匹配少的字符串。
参考:
http://www.runoob.com/python/python-reg-expressions.html