如何只匹配那些在它们前面有偶数个`%`的数字? [英] How to match only those numbers which have an even number of `%`s preceding them?

查看:150
本文介绍了如何只匹配那些在它们前面有偶数个`%`的数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想捕捉出现在字符串中任何位置的数字,并将其替换为(。+)。

I want to catch numbers appearing anywhere in a string, and replace them with "(.+)".

但我只想抓住那些有数字的数字在它们之前的偶数个。不用担心是否有任何周围的字符被抓住:我们可以使用捕获组来过滤掉这些数字。

But I want to catch only those numbers which have an even number of %s preceding them. No worries if any surrounding chars get caught up: we can use capture groups to filter out the numbers.

我无法提出ECMAscript正则表达式。

I'm unable to come up with an ECMAscript regular expression.

这是游乐场:

abcd %1 %%2 %%%3 %%%%4 efgh

abcd%12%%34%%%666%%%%11efgh

成功的捕获将表现如下:

A successful catch will behave like this:

如果你意识到,第三次尝试几乎正常。唯一的问题是在操场的第二行。
实际上,我想在那个表达式中说的是:

If you have realised, the third attempt is almost working. The only problems are in the second line of playground. Actually, what I wanted to say in that expression is:

匹配一个数字,前面是偶数个 s AND以下任一情况均为真:

Match a number if it is preceded by an even number of %s AND either of the following is true:


  • 上面的整个表达式前面是 nothing [缺少(未消耗或其他)字符]。

  • 上面的整个表达式前面都是以外的字符。

  • The above whole expression is preceded by nothing [absence of (unconsumed or otherwise) character].
  • The above whole expression is preceded by a character other than %.

有没有办法匹配角色的缺席

这是我在第三次尝试中使用 \0 尝试做的事情。

推荐答案

你可以使用(?:[^%\d] | ^ | \ b(?=%))(?:%%)* (\d +)作为模式,您的号码存储在第一个捕获组中。这也会对前面带有零%字符的数字进行处理。

You can use (?:[^%\d]|^|\b(?=%))(?:%%)*(\d+) as a pattern, where your number is stored into the first capturing group. This also treats numbers preceded by zero %-characters.

这将匹配偶数个%-signs,前提是:

This will match the even number of %-signs, if they are preceded by:


  • 既不是%也不是数字(所以我们不需要在%之前捕获最后一个数字,因为这对于像这样的链不起作用%% 1 %% 2

  • 字符串的开头

  • 字边界(因此任何单词字符) ,对于上面提到的连锁店

你可以看到它的实际效果这里

You can see it in action here

这篇关于如何只匹配那些在它们前面有偶数个`%`的数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆