javascript - 如果他们之前有文章,则丢弃正则表达式中的标记

标签 javascript regex

我希望我的正则表达式匹配“foo”和“bar”,但如果“foo”或“bar”以“a”、“an”或“the”开头则不匹配。

foobar 不保证位于字符串的开头或结尾。

匹配示例:

"end of Foo." [1 Match: Foo]
"end of bar." [1 Match: bar]
"The foo and bar" [1 Match: bar]
"foo bar" [2 Matches: foo, bar]

没有匹配的例子:

"foobar"
"foofoo"
"the foo"
"a bar"
"andbar"
"the foo goes to a bar."

我想我可能不得不做一个消极的事后回顾?如果是这样,这是否可以转化为对 JS 可移植性的负面前瞻?

我试过了

/(\bfoo\b|\bbar\b)(?!the|a(n)?)/igm

但这行不通。

非常感谢。

最佳答案

您可能会发现编写 Regex 来匹配向后拼写的单词并在匹配之前反转字符串的字符顺序会更容易。然后,您可以使用 Negative Look Ahead 模拟 Negative Look Behind

因此带有反向单词的正则表达式将是:

/\b(?:oof|rab)\b(?!eht|n?a)/igm

可视化:
Regular expression visualization

然后 JavaScript 是:

function ReverseString(str) {
    return str.split("").reverse().join("");
}

var myRegex = /\b(?:oof|rab)\b(?!eht|n?a)/igm;
var myString = "This is foo possibly";

alert( ReverseString(myString).match(myRegex) );

关于javascript - 如果他们之前有文章,则丢弃正则表达式中的标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22866199/

相关文章:

regex - 使用正则表达式删除任何空白或空白行

javascript - 字符串数组的字符串操作

python - 如何将单个正则表达式组与多个后续组组合

javascript - 如何处理大文件、NodeJS 流和管道

javascript - requireJS : Best way to add jQuery plugins?

javascript - 将变量传递给 Google 饼图

java - 方法参数的@Pattern注解

javascript - 如何在 VS Code 中为自定义文件扩展名启用 JavaScript IntelliSense?

javascript - 循环内循环 lodash

python - 如何从python中的字符串中提取一定长度的数字?