使用正则表达式匹配的短语后面的单词应该如何获取?

huangapple go评论82阅读模式
英文:

How do you get the word - after a regular expression matched phrase

问题

我想获得匹配短语后面的下一个单词。

示例:我想要改变我的疼痛阈值

-- "改变我的 ***"

let text = "我想要改变我的疼痛阈值";
let firstTriggerregEx = "(?:\\b|')(改变我的)(?:\\b|')";
const found2 = text.match(firstTriggerregEx);
console.log(found2);

这将返回一个匹配,但不包括后面的单词。

英文:

I want to get the next word after the matched phrase.

e.t. - I want to change my pain threshold

-- "change my ***"

let text = "I want to change my pain threshold"
    let firstTriggerregEx = "(?:\\b|')(change my)(?:\\b|')";
    const found2 = text.match(firstTriggerregEx);
    console.log(found2);

This will return a match, but not the word after

答案1

得分: 2

你可以使用以下模式:

(?<=\\bchange my )(\\w+)

第一部分是正向后查找。它确保后面的字符/组在指定模式之前。

第二部分包含了“单词字符”([a-zA-Z0-9_])的字符集,放在捕获组中,这样你可以稍后检索它。

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

英文:

You can use the following pattern:

(?&lt;=\\bchange my )(\\w+)

The first part is positive lookbehind. It ensures that the following character/group is preceded by the specified pattern.

The second part consists of the character set for "word characters" ([a-zA-Z0-9_]) within a capture group, so you can retrieve it later.

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

huangapple
  • 本文由 发表于 2023年7月18日 10:28:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/76709176.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定