【问题标题】:RegEx for matching N-digit plus consecutive numbers用于匹配 N 位加连续数字的正则表达式
【发布时间】:2019-05-15 12:21:06
【问题描述】:

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

输入字符串:Terrace 07541207031 RDL 18.02

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

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

【问题讨论】:

  • 用空字符串替换\d{4,}
  • @PushpeshKumarRajwanshi 我收到 SyntaxError: Invalid or unexpected token on the regex。
  • @user7331538 "Terrace 07541207031 RDL 18.02".replace(/\d{4,}/,"") 似乎工作正常,无论如何 Chrome 上都没有 SyntaxError。 ps,如果你想摆脱多余的空间,你也可以做/\s\d{4,}/
  • @Keith 我对正则表达式没有经验,以前我只使用 '\d{4,}' 而不是 '/\d{4,}/' 感谢您的帮助。

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


【解决方案1】:

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 中可视化您的表达式:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多