我有一个看起来像这样的文件
1234567:abcdefg:X
1234567:abcdefg:X
1234567:abcdefg:X
1234567:abcdefg:X
我需要将每行(X)的结尾字符替换为0。这似乎很简单,但是每次我使用regex时,它为null或regex.replace
不是函数。
目前,我有/.*:.*:(.*)/g
用于正则表达式
答案 0 :(得分:1)
您可以使用否定的字符类和捕获组将格式与冒号匹配,但最后一个字符除外。
^([^:]+:[^:]+:)\S$
^
字符串的开头(
捕获组1
[^:]+:[^:]+:
匹配2次而不是:
,然后匹配:使用negated character class )
关闭群组\S
匹配非空格字符$
字符串结尾在替换中,使用捕获组1后跟0
如果最后一个字符不能是冒号,请使用[^\s:]
代替\S
const regex = /^([^:]+:[^:]+:)\S$/gm;
const str = `1234567:abcdefg:X
1234567:abcdefg:X
1234567:abcdefg:X
1234567:abcdefg:X`;
const subst = `$10`;
const result = str.replace(regex, subst);
console.log(result);
答案 1 :(得分:0)
adiga 已回答。我添加了两个示例(基于 adigas 出色的答案/评论)。
const subject = `1234567:abcdefg:X
1234567:abcdefg:X
1234567:abcdefg:X
1234567:abcdefg:X`;
// Regular expression literal
const resultWithLiteral = subject.replace(/.$/gm, '0');
// Regular expression constructor
const expression = new RegExp(/.$/gm);
const resultWithConstructor = subject.replace(expression, '0');
function renderResults() {
const outputElements = document.querySelectorAll('pre');
outputElements[0].innerText = resultWithLiteral;
outputElements[1].innerText = resultWithConstructor;
};
<section>
<h1>Result with literal</h1>
<pre>
1234567:abcdefg:X
1234567:abcdefg:X
1234567:abcdefg:X
1234567:abcdefg:X
</pre>
</section>
<section>
<h1>Result with literal</h1>
<pre>
1234567:abcdefg:X
1234567:abcdefg:X
1234567:abcdefg:X
1234567:abcdefg:X
</pre>
</section>
<button onclick="renderResults();">Click to replace</button>