子字符串作为搜索 2 个单词的结果



我这里有很酷的正则表达式 正则表达式以匹配以任意顺序包含两个名称的字符串

^(?=.*bjackb)(?=.*bjamesb).*$

但是我需要子字符串作为结果。

例如:


  • hi jack here is james whats up
  • 我需要结果jack here is james

  • hi james here is jack whats up
  • 我需要结果james here is jack

我不能在正则表达式中使用杰克或詹姆斯超过 1 次。

我怎样才能得到它?

你可以在这里使用一个替代

^.*b(jackb.*bjames|jamesb.*bjack)b.*$

演示

在这种情况下,您要匹配的内容将显示在第一个捕获组中,即上面的演示链接。

/j[ack|ames]+ here is j[ack|ames]+/g

re = /j[ack|ames]+ here is j[ack|ames]+/g
let arr = [
"hi jack here is james whats up",
"hi james here is jack whats up"
]
console.log(arr.map(str => str.match(re)[0]))

最新更新