javascript - 用于匹配 N 位数字加连续数字的正则表达式

标签 javascript regex string regex-lookarounds regex-group

我正在尝试在 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 中可视化您的表情:

enter image description here

关于javascript - 用于匹配 N 位数字加连续数字的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56149250/

相关文章:

"a= object,object"的 Javascript 语法

javascript - 在 jquery 中使用 ajax 调用进行过滤和分页

python - Pandas 数据框可以有列表的数据类型吗?

python - 在通用列表中拆分 unicode 字符串

php - 了解 str_replace 和 strtr 在 php 中的工作原理

javascript - SignalR 异常 "Unrecognized user identity. The user identity cannot change during an active SignalR connection."

javascript - webpack 构建中出现意外标记 "export"

python - 添加一个值并使用 Notepad++ 对其求和

regex - 如果模式重复两次(非连续)匹配两个模式,正则表达式

python补充一个复杂的正则表达式