正则表达式用于匹配N位数字和连续数字

时间:2019-05-15 12:21:07

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

我正在尝试在node.js上使用javascript清理输入字符串。一些输入字符串可能包含我想删除的电话号码(或数字的随机序列)。例如:

输入字符串:Terrace 07541207031 RDL 18.02

清洗后,我希望字符串为:Terrace RDL 18.02

我想检测数字(例如大于4位数字)并将其删除。

1 个答案:

答案 0 :(得分:3)

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.  ");

RegEx

如果这不是您想要的表达式,则可以在regex101.com中修改/更改表达式。

RegEx电路

您还可以在jex.im中可视化您的表达式:

enter image description here

相关问题