首页 > 解决方案 > 用于替换两个单词之间的所有内容和新行的正则表达式

问题描述

我正在寻找一个 javascript 正则表达式来删除两个单词之间的所有行,包括单词。我可以找到这样的东西

Dim input = "one two three four START four five four five six END seven"
Dim output = Regex.Replace(input, "(?<=START.*)four(?=.*END)", "test")

这适用于 VB,此外,它不适用于多行,并且还会删除开头和结尾。

我该如何解决这个问题?

标签: javascriptregexregex-groupregex-greedy

解决方案


此表达式可以在新行之间捕获不需要的文本,start包括end新行:

START([\s\S]*)END

在此处输入图像描述

正则表达式描述图

此图将表达式可视化,如果您愿意,可以在此链接中测试其他表达式:

在此处输入图像描述

基本性能测试

此 JavaScript 片段返回 100 万次for循环的运行时以提高性能。您可以简单地删除 for ,这可能是您可能正在寻找的:

const repeat = 1000000;
const start = Date.now();

for (var i = repeat; i >= 0; i--) {
	const string = 'anything you wish before START four five four \n \n \n \n five six END anything you wish after';
	const regex = /(.*START)([\s\S]*)(.*END)/gm;
	var match = string.replace(regex, "$1 $3");
}

const end = Date.now() - start;
console.log("YAAAY! \"" + match + "\" is a match  ");
console.log(end / 1000 + " is the runtime of " + repeat + " times benchmark test.  ");

编辑

如果您希望用新行替换字符串中的一个单词,此表达式可能会有所帮助:

在此处输入图像描述


推荐阅读