python - 为什么匹配组存在但并不真正匹配?

标签 python regex python-2.7

为什么下一个代码与单词 SELECT 不匹配?

import re

re_q = r'(\d{4})-(\d{2})-(\d{2})\s(\d{2}):(\d{2}):(\d{2})\.*\d*\+\d{2}\s|\s(SELECT).*'

raw_q = "2014-01-23 15:28:32.993995+04 | SELECT query_start, query from pg_stat_activity WHERE state='active'"

m = re.match( re_q, raw_q )

for i in range( 1, 8 ):
    print "Group <{0}>: {1}".format( i, m.group( i ) )

输出:

Group <1>: 2014
Group <2>: 01
Group <3>: 23
Group <4>: 15
Group <5>: 28
Group <6>: 32
Group <7>: None

最佳答案

来自docs ,

'|'

A|B, where A and B can be arbitrary REs, creates a regular expression that will match either A or B. An arbitrary number of REs can be separated by the '|' in this way. This can be used inside groups (see below) as well. As the target string is scanned, REs separated by '|' are tried from left to right. When one pattern completely matches, that branch is accepted. This means that once A matches, B will not be tested further, even if it would produce a longer overall match. In other words, the '|' operator is never greedy. To match a literal '|', use \|, or enclose it inside a character class, as in [|].

| 在正则表达式语言中表示OR。您还必须使用 \ 来转义它。因此,\s|\s 应该是 \s\|\s。解决这个问题后,我得到了

Group <1>: 2014
Group <2>: 01
Group <3>: 23
Group <4>: 15
Group <5>: 28
Group <6>: 32
Group <7>: SELECT

关于python - 为什么匹配组存在但并不真正匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21307767/

相关文章:

python - 使用 ComputedProperty 安全吗?

java - java中如何组合多个正则表达式?

javascript - 当字符串包含括号时如何配置 RegExp

python - 如何将小数点后 1 位舍入为小数点后 2 位

python - 无法通过 python 网络抓取从 HTML 文件中提取#document

python - 如何修复 'CreateView is missing a QuerySet'

python - 在Python中捕获字符串中的数字并存储在数据框中

python - sre_constants.错误: unexpected end of regular expression - Should Work Fine

python - Win32api 没有在 python 中使用 GetCursorPos() 给出正确的坐标

Django 自定义按钮计数器