Javascript RegEx非捕获前缀 [英] Javascript RegEx non-capturing prefix
问题描述
我正在尝试使用Javascript中的RegEx进行一些字符串替换。该场景是一个单行字符串,包含长逗号分隔的数字列表,其中可能存在重复项。
I am trying to do some string replacement with RegEx in Javascript. The scenario is a single line string containing long comma-delimited list of numbers, in which duplicates are possible.
示例字符串为: 272, 2725,2726,272,2727,297,272
(结尾可能以逗号结尾也可能不以逗号结尾)
An example string is: 272,2725,2726,272,2727,297,272
(The end may or may not end in a comma)
在这个例子中,我正在尝试匹配整数272的每次出现。(预期3个匹配)
我试图使用的示例正则表达式是:(?:^ |,)272(?= $ |, )
In this example, I am trying to match each occurrence of the whole number 272. (3 matches expected)
The example regex I'm trying to use is: (?:^|,)272(?=$|,)
我遇到的问题是第二和第三场比赛包括我不想要的主要逗号。我很困惑,因为我认为(?:^ |,)
会匹配,但不会捕获。有人可以为我阐明这个吗?有趣的是,尾随的逗号被排除在结果之外,这就是我想要的。
The problem I am having is that the second and third matches are including the leading comma, which I do not want. I am confused because I thought (?:^|,)
would match, but not capture. Can someone shed light on this for me? An interesting bit is that the trailing comma is excluded from the result, which is what I want.
对于它的价值,如果我使用C#,则有语法执行我想要的前缀匹配:(?< = ^ |,)
但是,它似乎在JavaScript中不受支持。
For what it is worth, if I were using C# there is syntax for prefix matching that does what I want: (?<=^|,)
However, it appears to be unsupported in JavaScript.
最后,我知道我可以使用字符串拆分,数组操作和重新加入来解决它,但我想学习。
Lastly, I know I could workaround it using string splitting, array manipulation and rejoining, but I want to learn.
推荐答案
请改用字边界:
\b272\b
确保只有 272
匹配,但不是 2725
。
ensures that only 272
matches, but not 2725
.
(?:...)
匹配并且不捕获 - 但它匹配的任何内容都将成为整体匹配的一部分。
(?:...)
matches and doesn't capture - but whatever it matches will be part of the overall match.
外观断言 (?= ...)
是不同的:它只检查是否有可能(或不可能)匹配当前点的封闭正则表达式,但它不会添加整体比赛。
A lookaround assertion like (?=...)
is different: It only checks if it is possible (or impossible) to match the enclosed regex at the current point, but it doesn't add to the overall match.
这篇关于Javascript RegEx非捕获前缀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!