匹配没有前缀的数字

match numbers without a prefix

我需要正则表达式方面的帮助。

使用 javascript 我正在浏览文本文件的每一行,我想替换 [0-9]{ 6,9} 带有“*”,但是,我不想用前缀 100 替换数字。因此,像 1110022 这样的数字应该被替换(匹配),但是 1004567 不应该被替换(不匹配)。

我需要一个可以解决问题的表达式(只是匹配部分)。我不能使用 ^ 或 $ 因为数字可以出现在行的中间。

我已经尝试了 (?!100)[0-9]{6,9},但是没有用。

更多示例:

Don't match: 10012345

Match: 1045677

Don't match:

1004567

Don't match: num="10034567" test

Match just the middle number in the line: num="10048876" 1200476, 1008888

谢谢

您需要使用前导字边界来检查数字是否以某些特定数字序列开头:

\b(?!100)\d{6,9}

regex demo

在这里,100 是在单词边界之后检查的,而不是 数字内。

如果您只需要用一个星号替换匹配项,只需使用 "*" 作为替换字符串(参见下面的代码片段)。

var re = /\b(?!100)\d{6,9}/g; 
var str = 'Don\'t match: 10012345\n\nMatch: 1045677\n\nDon\'t match:\n\n1004567\n\nDon\'t match: num="10034567" test\n\nMatch just the middle number in the line: num="10048876" 1200476, 1008888';
document.getElementById("r").innerHTML = "<pre>" + str.replace(re, '*') + "</pre>";
<div id="r"/>

或者,如果您需要用 * 替换每个数字,您需要在 replace 中使用回调函数:

String.prototype.repeat = function (n, d) {
    return --n ? this + (d || '') + this.repeat(n, d) : '' + this
};

var re = /\b(?!100)\d{6,9}/g; 
var str = '123456789012 \nDon\'t match: 10012345\n\nMatch: 1045677\n\nDon\'t match:\n\n1004567\n\nDon\'t match: num="10034567" test\n\nMatch just the middle number in the line: num="10048876" 1200476, 1008888';
document.getElementById("r").innerHTML = "<pre>" + str.replace(re, function(m) { return "*".repeat(m.length); }) + "</pre>";
<div id="r"/>

repeat函数借用自BitOfUniverse's answer