正则表达式在第 n 个到最后一个单词的特定字符串匹配字符串

regex match strings with specific string at nth to last word

我正在尝试使用正则表达式将字符串与 "nth" 处的特定字符串匹配到最后一个词。

在这种情况下,字符串 "call" 位于倒数第二个单词中。

我尝试过的最成功的事情:

/.*(?=.*call.*)(\w+)\s(\w+)$/

我得到的回复和我正在寻找的内容:

建议?

您的主要问题是您使用的是前瞻性 (?=...),这令人困惑。这与您的正则表达式相匹配,它必须后跟单词 call。也许您打算使用非捕获组:(?:...)?

/.*(?:.*call.*)(\w+)\s(\w+)$/

你实际上并不需要它,因为未分组的东西也不会捕获:

/.*call.*(\w+)\s(\w+)$/

在你改变之后,你遇到了在 "call" 你匹配之后的问题 "any characters any number of times followed by 1 or more word characters followed by a space and 1 or more word characters".

那将匹配:

call with lots of words after it as long as there are two at the end

但不是:

call me

因为通话后不会有至少两个字。

我想你想匹配以 "call followed by any number of word characters, a space, and any number of word characters":

结尾的字符串
/.*call(\w*)\s(?:\w+)$/

如果您确实想要匹配 "call" 和后续单词,您可以适当地更改 capturing/non-capturing 组。

Here's an example

如果我理解正确的话,你不需要使用 lookahead/behind...

你只需要正则表达式来检查你是否有东西,然后 "call",然后最终是别的东西,然后是空格,然后是另一个词和字符串的结尾。

/.*call[^\s]*\s[A-Za-z]+$/

我想你需要这个正则表达式。