我在 MongoDB v2.2.4 的命令行客户端中使用 Javascript 来运行以下正则表达式反向引用:
> /([AB])([AB])/("BA")
[ "BA", "B", "A" ]
我原以为我应该得到 ["B","A"] 但我在数组的开头得到了一个额外的元素“BA”。我在Python中尝试了相同的正则表达式反向引用,返回结果如下:
>>> re.search('([AB])([AB])','BA').groups()
('B', 'A')
那么,我可以说MongoDB中Javascript的正则表达式反向引用的结果是错误的吗?
最佳答案
MongoDB 结果包括整个匹配字符串,或组 0,以及组 1 和 2。
Python .groups()
方法仅返回捕获的组。 .group()
方法在没有参数的情况下也会返回组 0:
>>> re.search('([AB])([AB])', 'BA').groups()
('B', 'A')
>>> re.search('([AB])([AB])', 'BA').group()
'BA'
>>> re.search('([AB])([AB])', 'BA').group(1)
'B'
>>> re.search('([AB])([AB])', 'BA').group(2)
'A'
>>> re.search('([AB])([AB])', 'BA').group(0)
'BA'
这是documented in the re
module documentation :
Return a tuple containing all the subgroups of the match, from 1 up to however many groups are in the pattern.
对于 .group()
方法:
Returns one or more subgroups of the match. If there is a single argument, the result is a single string; if there are multiple arguments, the result is a tuple with one item per argument. Without arguments, group1 defaults to zero (the whole match is returned).
请注意,表达式中没有反向引用。反向引用看起来像这样:
'([AB])\1'
其中 \1
指的是其之前的捕获组。反向引用将仅匹配与引用组匹配的完全相同的字符。
演示:
>>> re.search(r'([AB])\1', 'BA')
>>> re.search(r'([AB])\1', 'BB')
<_sre.SRE_Match object at 0x107098210>
请注意如何仅匹配 BB
,而不是 BA
。
您也可以使用命名组:
'(?P<a_or_b>[AB])(?P=a_or_b)'
其中 a_or_b
是组名称。
关于javascript - 正则表达式反向引用的结果正确吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16701013/