简体   繁体   English

正则表达式只匹配完整的单词,但如果用引号括起来则不会

[英]Regex match only full word, but not if wrapped in quotes

I'd like to match only the full word, but not if wrapped in quotes 我想只匹配完整的单词,但如果用引号括起来则不会

for example: word 例如: word

but not: "word" 但不是: "word"

The first can be matched with /\\bword\\b/ 第一个可以与/\\bword\\b/匹配

For the second this is the closest I've gotten, the problem is it prevents matches from "word word" and "word" , I only want it not to match if it is "word" 对于第二个,这是我得到的最接近的,问题是它阻止了"word word""word"匹配,我只希望它不匹配,如果它是"word"

(?!")\bword\b(?!")
\b(\w+(?!")|(?<!")\w+)\b

See it in action 看到它在行动

The idea is to match the word if it is not followed or preceded by " (using negative lookarounds ), not the two at the same time. 如果没有遵循或先于" (使用负面外观 ),而不是同时使用两个词,则匹配该词。

You can use this regex in PHP: 你可以在PHP中使用这个正则表达式:

"\w+"(*SKIP)(*F)|\b\w+\b

This will fail every "word" using (*SKIP)(*F) directives and will match each word otherwise. 这将使用(*SKIP)(*F)指令使每个"word"失败,否则将匹配每个单词。

RegEx Demo RegEx演示

Try 尝试

/((\")*word$)|(^word(\")*)/g

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

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

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