我正在尝试在 node.js 上使用 javascript 清理输入字符串。一些输入字符串可能包含我想删除的电话号码(或随机数字序列)。例如:
输入字符串:Terrace 07541207031 RDL 18.02
清理后我希望字符串为:Terrace RDL 18.02
我想检测数字(比如大于 4 位数字)并将其删除。
最佳答案
This expression可能与您所需的输入匹配。
(\s)([0-9]{4,})(\s?)
如果你想匹配任何4位数字加数字,你可以简单地删除左右空格检查边界:
([0-9]{4,})
JavaScript 演示
const regex = /(\s)([0-9]{4,})(\s?)/gm;
const str = `Terrace 07541207031 RDL 18.02
Terrace 07541 RDL 18.02
Terrace 075adf8989 RDL 18.02
Terrace 075adf898 RDL 18.02
075898 RDL 18.02
Terrace RDL 98989https://regex101.com/r/FjZqaF/1/codegen?language=javascript`;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
性能测试
此脚本根据表达式返回输入字符串的运行时间。
const repeat = 1000000;
const start = Date.now();
for (var i = repeat; i >= 0; i--) {
const regex = /(.*\s)([0-9]{4,})(\s.*)/gm;
const str = "Terrace 07541207031 RDL 18.02";
const subst = `$1$3`;
var match = str.replace(regex, subst);
}
const end = Date.now() - start;
console.log("YAAAY! \"" + match + "\" is a match 💚💚💚 ");
console.log(end / 1000 + " is the runtime of " + repeat + " times benchmark test. 😳 ");
正则表达式
如果这不是您想要的表达式,您可以在 regex101.com 中修改/更改您的表达式.
正则表达式电路
您还可以在 jex.im 中可视化您的表情:
关于javascript - 用于匹配 N 位数字加连续数字的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56149250/