javascript - 正则表达式反向引用的结果正确吗?

标签 javascript python regex mongodb

我在 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/

相关文章:

python - 基于其他数组Python更新数组

Python 多行正则表达式分隔符

c# - 使用正则表达式将插值字符串转换为 string.Format

javascript - 有没有办法从元素中获取 SlickGrid 的实例

python - 从字符串中删除非字母数字但保留编码的非 ASCII 字符 åäö

javascript - 使用 .map() 在 jquery 中分组

python - 将 nD numpy 数组折叠成一维数组

java - 将先前捕获的组与正则表达式匹配(反向引用?)

javascript - 以Redux状态: reflection of API object vs.简化形式状态存储数据

来自不同作用域变量的 javascript 回调函数未定义