import re
line = "Cats are smarter than dogs"
m = re.match( r'(.*) are (.*?) .*', line)
print m.group()
print m.group(1)
print m.group(2)
import re
pattern = re.compile(r'(.*) are (.*?) .*')
m = pattern.match("Cats are smarter than dogs")
print m.group()
print m.group(1)
print m.group(2)
这两种写法有些啥区别?为啥要定义两种写法呢?
1
wwqgtxx 2018 年 8 月 25 日
def match(pattern, string, flags=0):
"""Try to apply the pattern at the start of the string, returning a Match object, or None if no match was found.""" return _compile(pattern, flags).match(string) 这是标准库的定义,所以说你的两种写法本质上是一样的 |
2
imn1 2018 年 8 月 25 日
oop 当然是为了复用啦
你以为正则都是只用一次就舍弃? |
4
delectate 2018 年 8 月 25 日
楼主这明显还是 py2 的写法;第二种是效率更高一点点。
|
5
wocanmei 2018 年 8 月 25 日 via iPhone
第一种每次调用 match 都有一个正则的编译时间,编译是指正则相当于一种简单的语言,需要对其进行解析,形成某种结构比如语法树,才好对字符串进行匹配,第二种是提前对正则进行了编译,而不是每次调用都有,效率比前者高点
|
6
wwqgtxx 2018 年 8 月 25 日
@glacer
@wocanmei 其实 python3 的 re.py 中_compile()函数内部是有个_cache 的 https://github.com/python/cpython/blob/3.7/Lib/re.py#L268 所以并不会每次调用都会编译一遍 |
8
PulpFunction 2018 年 8 月 25 日
俩种写法书上看过,好像只推荐了其中一种
|
9
PythonAnswer 2018 年 8 月 26 日 via iPhone
第二种更好。
|
10
wizardoz 2018 年 8 月 26 日
就这个例子来说没啥区别,因为两种都是编译一次用了一次。但是如果同一个正则式反复用的话,可以调用一个 compile,然后反复用 pattern.match 可以减少多次 compile 的时间。
|
11
frostming 2018 年 8 月 27 日
第一种,每次你 match 的时候都要执行一遍 pattern=re.compile(r'(.*) are (.*?) .*')
第二种,你先 compile 好了以后就不用每次都 compile 了,效率更高一点 你只用一次这个正则没什么区别,多次使用时有区别 |