简体   繁体   English

正则表达式\\ b匹配具有特殊字符的字符串

[英]Regex \b matching strings with special characters

Having issues with \\b expression that shouldn't match with words with special characters. \\ b表达式出现问题,不应与带有特殊字符的单词匹配。

I have this regex 我有这个正则表达式

\bstr=flavor\b

I was reading about escaping special characters but I'm not sure where to put it. 我正在阅读有关转义特殊字符的信息,但不确定将其放在何处。

My goal is for the regex not to match the following string 我的目标是使正则表达式不匹配以下字符串

str=flavor%20sweet --> Shouldn't match (1) 
str=flavorsweet --> shouldn't match (2)
declare str=flavor --> should match (3)

2 and 3 already works with the current regex but 1 I'm having issues with since it still matches where it should take into account the % 2和3已经可以使用当前的正则表达式,但是1存在问题,因为它仍然与应考虑%匹配

How should I change my regex to have it treat % as a character? 我应该如何更改我的正则表达式以使其将%视为字符?

If your regex engine accept negative lookahead, you can use: 如果您的正则表达式引擎接受否定的前瞻,则可以使用:

\bstr=flavor\b(?!%)

to force that the character directly following your str=flavor is not a % char. 强制紧随您的str=flavor之后的字符不是% char。

demo: https://regex101.com/r/kSmLzW/1 演示: https : //regex101.com/r/kSmLzW/1

Also you could add [ \\t]* around the = char to accept str = flavor for example. 另外,您可以在= char周围添加[ \\t]*以接受str = flavor

This gives the regex: ( \\bstr[ \\t]*=[ \\t]*flavor\\b(?!%) ) 这给出了正则表达式:( \\bstr[ \\t]*=[ \\t]*flavor\\b(?!%)

For older versions of JS you can use: 对于旧版JS您可以使用:

\b(str=flavor)\b(?:[^%]|$)

demo: https://regex101.com/r/kSmLzW/2 where you can refer back to match via back reference if necessary. 演示: https//regex101.com/r/kSmLzW/2 ,如有必要,您可以在此处通过反向引用进行反向匹配。 Also if there are other characters that you do not want to be taken into account in top of the % you can just add them in the character range exception definition [^] 另外,如果您不想在%上方考虑其他字符,则可以将它们添加到字符范围异常定义[^]

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

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