正则表达式:如何“退一步”
我在编写产生此结果的正则表达式时遇到一些麻烦:
Mike1, misha1,2, miguel1,2,3,4,5, 6,7,18 和 Michea2,3
如何在正则表达式中后退并丢弃最后一个匹配项?也就是说,我需要在空格前加一个逗号才能不匹配。这就是我想出的...
\d+(,|\r)
Mike1, misha1,2, miguel1,2,3,4,5,6,7,18 、 和迈克尔2,3
I am having some trouble cooking up a regex that produces this result:
Mike1, misha1,2, miguel1,2,3,4,5,6,7,18, and Michea2,3
How does one step back in regex and discard the last match? That is I need a comma before a space to not match. This what I came up with...
\d+(,|\r)
Mike1, misha1,2, miguel1,2,3,4,5,6,7,18, and Micheal2,3
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您所询问的正则表达式功能称为正向后查找。但就你的情况而言,我认为你不需要它。试试这个:
在您的示例中,这将匹配逗号分隔的数字列表,并排除名称和尾随逗号和空格。
下面是用 PHP 编写的一小段测试代码,用于验证您的输入:
输出:
The regex feature you're asking about is called a positive lookbehind. But in your case, I don't think you need it. Try this:
In your example, this will match the comma delimited lists of numbers and exclude the names and trailing commas and whitespace.
Here is a short bit of test code written in PHP that verifies it on your input:
outputs:
我相信
\d+,(?!\s)
会做你想要的。?!
是一个 否定先行,仅匹配?!
后面的内容没有出现在搜索字符串的这个位置。或者,如果您想匹配以逗号分隔的数字列表(不包括最后的逗号),请使用
\d+(?:,\d+)*
。I believe
\d+,(?!\s)
will do what you want. The?!
is a negative lookahead, which only matches if what follows the?!
does not appear at this position in the search string.Or if you want to match the comma-separated list of numbers excluding the final comma use
\d+(?:,\d+)*
.