Javascript Regex仅替换第一个匹配项

Javascript Regex only replacing first match occurence

本文关键字:第一个 替换 Regex Javascript      更新时间:2023-09-26

我正在使用正则表达式将wiki标记代码转换为可复制的可粘贴纯文本,并使用javascript来完成这项工作。

然而,javascript的正则表达式引擎的行为与我以前使用过的以及我每天使用的Notepad++中的正则表达式有很大不同。

例如,给定一个测试字符串:

==Section Header==
===Subsection 1===
# Content begins here.
## Content continues here.

我想以结束

Section Header
Subsection 1
# Content begins here.
## Content continues here.

只需删除所有等号。

我从正则表达式设置开始:

var reg_titles = /(^)(=+)(.+)(=+)/

此正则表达式搜索以一个或多个等于开头、以另一组一个或更多个等于开头的行。Rubular显示它准确地匹配了我的线条,并且在比赛中间没有抓住等号。http://www.rubular.com/r/46PrkPx8OB

基于正则表达式替换字符串的代码

var lines = $('.tb_in').val().split(''n'); //use jquery to grab text in a textarea, and split into an array of lines based on the 'n 
for(var i = 0;i < lines.length;i++){
  line_temp = lines[i].replace(reg_titles, "");
  lines[i] = line_temp; //replace line with temp
}
$('.tb_out').val(lines.join("'n")); //rejoin and print result

不幸的是,我的结果是:

Section Header==
Subsection 1===
# Content begins here.
## Content continues here.

我不明白为什么regex replace函数在找到多个匹配项时,似乎只替换它找到的第一个实例,而不是所有实例。

即使我的正则表达式更新为:var reg_titles=/(={2,})/

"找到任意两个或两个以上的相等项",输出仍然相同。它只进行一次替换,而忽略所有其他匹配。

没有一个regex表达式执行器对我来说是这样的。多次运行相同的replace没有效果。

关于如何让我的字符串替换函数替换匹配正则表达式的所有实例,而不仅仅是第一个实例,有什么建议吗?

^=+|=+$

你可以用这个。不要忘记添加gm标志。替换为``。请参阅演示。

http://regex101.com/r/nA6hN9/28

添加g修饰符进行全局搜索:

var reg_titles = /^(=+)(.+?)(=+)/g

您的正则表达式非常复杂,但实际上并没有完成您要做的事情。:)您可以尝试这样的方法:

var reg_titles = /^=+(.+?)=+$/;
lines = $('.tb_in').val().split(''n');
lines.forEach(function(v, i, a) {
    a[i] = v.replace(reg_titles, '$1');
})
$('.tb_out').val(lines.join("'n"));