通过该re.DEBUG标志可以了解 Python 中正则表达式模式的内部工作原理,例如:
import re
re.compile(r"(a(?:b)){1,3}(c)", re.DEBUG)
Run Code Online (Sandbox Code Playgroud)
返回:
MAX_REPEAT 1 3
SUBPATTERN 1 0 0
LITERAL 97
LITERAL 98
SUBPATTERN 2 0 0
LITERAL 99
0. INFO 4 0b0 3 7 (to 5)
5: REPEAT 11 1 3 (to 17)
9. MARK 0
11. LITERAL 0x61 ('a')
13. LITERAL 0x62 ('b')
15. MARK 1
17: MAX_UNTIL
18. MARK 2
20. LITERAL 0x63 ('c')
22. MARK 3
24. SUCCESS
Run Code Online (Sandbox Code Playgroud)
在哪里可以找到操作码(SUBPATTERN、MAX_REPEAT 等)的含义?其中一些是不言自明的,但整体目的尚不清楚。是什么1 0 0意思SUBPATTERN 1 0 0 …
我有一个相当大的字符串(~700k),我需要运行10个正则表达式并计算任何正则表达式的所有匹配项.我的快速和肮脏的impl是做一些像re.search('(expr1)|(expr2)| ...'),但我想知道我们是否通过循环匹配看到任何性能提升:
换句话说,我想比较以下的表现:
def CountMatchesInBigstring(bigstring, my_regexes):
"""Counts how many of the expressions in my_regexes match bigstring."""
count = 0
combined_expr = '|'.join(['(%s)' % r for r in my_regexes])
matches = re.search(combined_expr, bigstring)
if matches:
count += NumMatches(matches)
return count
Run Code Online (Sandbox Code Playgroud)
VS
def CountMatchesInBigstring(bigstring, my_regexes):
"""Counts how many of the expressions in my_regexes match bigstring."""
count = 0
for reg in my_regexes:
matches = re.search(reg, bigstring)
if matches:
count += NumMatches(matches)
return count
Run Code Online (Sandbox Code Playgroud)
我将不再懒惰并明天进行一些测试(并发布结果),但我想知道答案是否会跳到真正了解正则表达式如何工作的人身上:)
我需要从HTML文件中快速提取文本.我使用以下正则表达式而不是完整的解析器,因为我需要快速而不是准确(我有超过1 TB的文本).分析器显示我的脚本中的大部分时间都花在re.sub过程中.什么是加快我的过程的好方法?我可以在C中实现一些部分,但我想知道这是否有用,因为在 re.sub中花费的时间,我认为这将有效实现.
# Remove scripts, styles, tags, entities, and extraneous spaces:
scriptRx = re.compile("<script.*?/script>", re.I)
styleRx = re.compile("<style.*?/style>", re.I)
tagsRx = re.compile("<[!/]?[a-zA-Z-]+[^<>]*>")
entitiesRx = re.compile("&[0-9a-zA-Z]+;")
spacesRx = re.compile("\s{2,}")
....
text = scriptRx.sub(" ", text)
text = styleRx.sub(" ", text)
....
Run Code Online (Sandbox Code Playgroud)
谢谢!
我有一个正则表列表,我想从中提取那些相当于字符串比较的正则表达式.
例如,那些正则表达式相当于一个简单的字符串比较:
[r"example", # No metacharacters
r"foo\.bar"] # . is not a metacharacter because it is escaped
Run Code Online (Sandbox Code Playgroud)
而那些正则表达式不是:
[r"e.ample", # . is a metacharacter
r"foo\\.bar"] # . is a metacharacter because it is not escaped
Run Code Online (Sandbox Code Playgroud)
根据https://docs.python.org/2/howto/regex.html,有效元字符列表是. ^ $ * + ? { } [ ] \ | ( ).
我即将构建一个正则表达式,但它看起来有点复杂.我想通过检查re对象或其他东西是否有快捷方式.