Javascript Regex:积极的Lookbehind替代方案 [英] Javascript Regex: Positive Lookbehind alternative
问题描述
寻找替代方案:
(?<=\.\d\d)\d
(一段时间后匹配第三位数字)
(Match 3rd digit after a period)
我知道我可以通过其他方法解决它,但我必须使用正则表达式,更重要的是我必须在字符串上使用replace,而不添加回调。
I'm aware I can solve it by using other methods but I have to use a Regular Expression and more importantly I have to use replace on the string, without adding a callback.
推荐答案
以消耗模式转换lookbehind并使用捕获组:
Turn the lookbehind in a consuming pattern and use a capturing group:
并按如下所示使用它:
var s = "some string.005";
var rx = /\.\d\d(\d)/;
var m = s.match(/\.\d\d(\d)/);
if (m) {
console.log(m[1]);
}
编辑:
从<去除 3
code> str.123 使用您当前的规范,使用相同的捕获方法:捕获您需要的内容并使用<$ c恢复结果中捕获的文本$ c> $ n 替换模式中的反向引用,只需匹配您需要删除的内容。
To remove the 3
from the str.123
using your current specifications, use the same capturing approach: capture what you need and restore the captured text in the result using the $n
backreference(s) in the replacement pattern, and just match what you need to remove.
var s = "str.123";
var rx = /(\.\d\d)\d/;
var res = s.replace(rx, "$1");
console.log(res);
这篇关于Javascript Regex:积极的Lookbehind替代方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!