javascript - RegEx 用于检查多个匹配项
问题描述
我想匹配字符串中的所有出现。
例子:
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+
在比赛中没有价值的原因。
我该如何解决这个问题?
解决方案
你需要某种递归正则表达式来实现你想要得到的东西,你可以使用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)
推荐阅读
- git-stash - 是否可以存放暂存区,但不能存放工作树?
- javascript - 尝试将代码注入 Microsoft Teams 时出错
- python - 如何在解码为 [UNK] bert tokenizer 的 vocab.txt 中添加标记
- python - 我设置 evaluate=False,买 SymPy 的 parse_expr 仍然计算表达式
- javascript - 如何手动发出事件到间隔?
- c# - 在 MainWindow C# WPF 中显示结果
- javascript - chartjs 并对特定元素进行 onClick 操作?
- c++ - C++ 代码错误 - 没有运算符“<<”与这些操作数匹配
- python - OpenCV 系统错误
返回带有错误集的结果 - mongodb - 嵌套数组中的 $lookup 字段