gpt4 book ai didi

javascript Reg Backwards 不起作用

转载 作者:行者123 更新时间:2023-12-01 03:30:27 26 4
gpt4 key购买 nike

我想匹配字符串中的数字:'abc@2003,或其他@2017'我想通过 match 函数获得结果 [2003, 2007]。

let strReg = 'abc@2003, or something else @2017';
let reg = new RegExp(/(?=(@\d+))\1/);
strReg.match(reg) //[ '@2003 ', '@2017 ' ]
let reg1 = new RegExp(/(?=@(\d+))\1/)
strReg.match(reg1) //null, but I expect [2003, 2007]

结果主要是“\1”匹配“?=”之后,?=()\1 有效,?=@()\1 无效。

javascript只支持向后,我该怎么做才能匹配'@'但忽略它?

最佳答案

我认为您想要一个结果数组,所以...

var s = "abc@2003, or something else @2017 not the 2001 though";
var re = /@(\d+)/g;
var result = [];
var match = re.exec(s);
while (match !== null) {
result.push(parseInt(match[1]));
match = re.exec(s);
}

console.log(result);

输出:

Array [ 2003, 2017 ]

match(0) 是整个匹配,match(1) 是捕获的组。

另请参阅How do you access the matched groups in a JavaScript regular expression?

灵感来自javascript regex - look behind alternative? ,如果你想把它当作一句简单的话:

var re = /(\d+)(?=@)/g; /* write the regex backwards */
var result = [];
s.split('').reverse().join('').match(re).forEach(function (el) { result.push(parseInt(el.split('').reverse().join(''))); });
console.log(result.reverse());

警告:Who wrote this programing saying? “Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live.”

关于javascript Reg Backwards 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44565443/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com