javascript - 用于替换两个单词之间的所有内容和新行的正则表达式
问题描述
我正在寻找一个 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,此外,它不适用于多行,并且还会删除开头和结尾。
我该如何解决这个问题?
解决方案
此表达式可以在新行之间捕获不需要的文本,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. ");
编辑
如果您希望用新行替换字符串中的一个单词,此表达式可能会有所帮助:
推荐阅读
- jquery - JQuery - 删除类后隐藏元素
- javascript - 如果返回数据错误,如何防止函数运行
- vb.net - 如何使用变量来引用文本框?
- pytest - 是否可以在 pytest_generate_tests() 中使用夹具?
- vba - 使用 Access 中的组合框过滤导航子表单
- python - Python 中的 list.copy() 返回相同的引用?
- python - In a Pandas dataframe how do I calculate the median value for each decile within each month
- system.reactive - 来自 Observable.FromEventPattern 的不兼容委托异常
- python - 将浮点数转换为特定子列表中的整数
- osgi - RedHat Fuse 7.5 - 无法部署功能