简体   繁体   English

如果句子前面有特定单词,则匹配一个单词

[英]Match a word if there a specific word in the sentence before

I would like to match a word if there a specific word before in a sentence, for instance: 我想匹配一个单词,如果句子中之前有一个特定的单词,例如:

test1 foo test2 bar test1 foo test2栏

I would like to match bar if foo is in the sentence before (and/or after bar ). 我想匹配bar ,如果foo是在判决之前(和/或之后bar )。

I tried: 我试过了:

(?<=(foo ([\w ]+)(?= bar)))bar

But doesn't work, the regex is incorrect because of + in lookbehind... 但是不起作用,正则表达式不正确,因为后面的+ ...

Could you please help me, thanks 您能帮我吗,谢谢

If you have to use one regex, you can just simply move the [\\w ]+ out of the lookbehind. 如果必须使用一个正则表达式,则只需将[\\w ]+从后面移开即可。 Then use an alternation to look for the word bar (on its own, not as part of another word) followed by foo as well: 然后使用替代项查找单词bar(单独查找,而不作为另一个单词的一部分),后跟foo:

((?<=foo)[\w ]+\bbar\b|\bbar\b[\w ]+(?=foo))

Regex101 demo Regex101演示

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

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