首页 > 解决方案 > 正则表达式 - 匹配多个不跟数值的特定字符实例

问题描述

我需要一个正则表达式查询来匹配以下内容:

hello%20world //Wont match
hello % dog //Will match
hello %20 world //Wont match
hello %% world //Will match but twice (Wont match as whole word of %%, will match single "%" and then the second "%")

我正在使用正则表达式替换任何不带数字的“%”匹配项。如果它包含“%%”,我也想用“A”替换这两个,所以我得到“AA”而不是“A”。

我的正则表达式尝试:

%[^0-9]

https://regex101.com/r/Z9N7QJ/1

问题是它的匹配,但也与下一个字符匹配,所以我的字符串“Hello % world”匹配“%”。我的“%%”被匹配为一对而不是单打。

谢谢。

标签: regex

解决方案


您可以在此处使用负前瞻:

/%(?!\d)/

更新的 RegEx 演示

Lookahead 是零宽度匹配,但您的正则表达式%[^0-9]相反也会消耗下一个非数字字符。


推荐阅读