【问题标题】:RegEx for checking multiple matches [duplicate]用于检查多个匹配项的正则表达式 [重复]
【发布时间】:2019-10-07 20:47:27
【问题描述】:

我想匹配字符串中的所有匹配项。

示例:

pc+pc2/pc2+pc2*rr+pd

我想检查有多少匹配的pc2 值和正则表达式是before and after special character 存在。

var str = "pc+pc2/pc2+pc2*rr+pd"; 
var res = str.match(new RegExp("([\\W])pc2([\\W])",'g'));

但我只有+pc2/+pc2*/pc2+ 没有参与进来。

问题在于第一个匹配 / 已删除。所以在那之后,它从pc2+pc2*rr+pd开始检查。这就是为什么/pc2+ 值没有进入匹配项。

我该如何解决这个问题?

【问题讨论】:

  • 你也只想要计数或匹配?
  • 我想在数组中匹配。
  • 或者,如果你的意思是重叠匹配,let res = [..."pc+pc2/pc2+pc2*rr+pd".matchAll(/(?=(\Wpc2\W))\W/g)] 然后Array.from(res, x => x[1])
  • @WiktorStribiżew 不工作。
  • @WiktorStribiżew 这不是一个重复的问题。我想要+pc2/+pc2*/pc2+。收到了吗?

标签: javascript regex string regex-group regex-greedy


【解决方案1】:

你需要某种递归正则表达式来实现你想要得到的东西,你可以使用exec来操作lastIndex,如果字符串中的值为p

let regex1 = /\Wpc2\W/g;
let str1 = 'pc+pc2/pc2+pc2*rr+pd';
let array1;
let op = []
while ((array1 = regex1.exec(str1)) !== null) {
  op.push(array1[0])
  if(str1[regex1.lastIndex] === 'p'){
    regex1.lastIndex--;
  }
}


console.log(op)

【讨论】:

  • 它正在工作,但if(str1[regex1.lastIndex] === 'p'){ 这是pc2 的静态代码。因为我只匹配 pc2 而不是其他值。
  • @DhadukMitesh 您可以使用支持递归正则表达式的正则表达式库,您甚至可以将上述函数设为通用,我已根据您指定的问题添加了答案
  • 是的,@code。但我希望动态代码找到价值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-01
  • 2017-01-15
  • 1970-01-01
  • 2015-12-26
  • 1970-01-01
相关资源
最近更新 更多