简体   繁体   English

正则表达式命名为Capture Group的替代方案,前导$字符

[英]Regular expression Named Capture Group alternatives with leading $ character

I have two groups web and var, with the following alternative strings: aliceblue, yellow and $aliceblue, $yellow 我有两组web和​​var,使用以下替代字符串:aliceblue,yellow和$ aliceblue,$ yellow

I am able to get matches for aliceblue and yellow in group web but i am not getting matches for $aliceblue or $yellow in group var. 我能够在组Web中获得aliceblue和yellow的匹配项,但在组var中却没有获得$ aliceblue或$ yellow的匹配项。

re = '/(?x)(?i)(?<![@#$.\-_])(?:\b(?P<var>$aliceblue|$yellow)\b(?!\()|\b(?P<web>aliceblue|yellow)\b(?!\())(?![@#$.\-_])/m';
str = 'aliceblue';

I tried to escape the $ character without success 我试图逃脱$字符而没有成功

re = '/(?x)(?i)(?<![@#$.\-_])(?:\b(?P<var>\$aliceblue|\$yellow)\b(?!\()|\b(?P<web>aliceblue|yellow)\b(?!\())(?![@#$.\-_])/m';
str = '$aliceblue';

How can I change the regex so I get a match for $aliceblue in group var and aliceblue in group web? 如何更改正则表达式,以便在组var和组web中的$ aliceblue和aliceblue中找到匹配项?

Besides escaping the $ in your regex, you also need to get rid of \\b just before it, as $ is not part of word character \\w which is [a-zA-Z0-9_] 除了在正则表达式中转义$之外,还需要在\\b之前删除\\b ,因为$不属于单词字符\\w一部分,后者是[a-zA-Z0-9_]

Check this demo with \\b removed from your regex 从正则表达式中删除\\ b来检查此演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM