gpt4 book ai didi

javascript - 替换数据 block 中的多个模式

转载 作者:可可西里 更新时间:2023-11-01 02:52:38 27 4
gpt4 key购买 nike

我需要找到在单个文本 block 上匹配多个正则表达式的最有效方法。举一个我需要的例子,考虑一段文本:

“你好,多么美好的一天”

我想将 Hello 替换为“Bye”,将“World”替换为 Universe。当然,我总是可以在循环中执行此操作,使用各种语言可用的 String.replace 函数之类的东西。

但是,我可能有一大块包含多个字符串模式的文本,我需要对其进行匹配和替换。

我想知道我是否可以使用正则表达式来高效地执行此操作,还是我必须使用像 LALR 这样的解析器。

我需要在 JavaScript 中执行此操作,因此如果有人知道可以完成此操作的工具,我们将不胜感激。

最佳答案

编辑

在我最初的回答(下)6 年后,我会以不同的方式解决这个问题

function mreplace (replacements, str) {
let result = str;
for (let [x, y] of replacements)
result = result.replace(x, y);
return result;
}

let input = 'Hello World what a beautiful day';

let output = mreplace ([
[/Hello/, 'Bye'],
[/World/, 'Universe']
], input);

console.log(output);
// "Bye Universe what a beautiful day"

与之前的答案相比,这具有巨大的优势,后者要求您将每个匹配项写两次。它还使您可以单独控制每场比赛。例如:

function mreplace (replacements, str) {
let result = str;
for (let [x, y] of replacements)
result = result.replace(x, y);
return result;
}

let input = 'Hello World what a beautiful day';

let output = mreplace ([
//replace static strings
['day', 'night'],
// use regexp and flags where you want them: replace all vowels with nothing
[/[aeiou]/g, ''],
// use captures and callbacks! replace first capital letter with lowercase
[/([A-Z])/, $0 => $0.toLowerCase()]

], input);

console.log(output);
// "hll Wrld wht btfl nght"


原始答案

Andy E的答案可以修改,使添加替换定义更容易。

var text = "Hello World what a beautiful day";
text.replace(/(Hello|World)/g, function ($0){
var index = {
'Hello': 'Bye',
'World': 'Universe'
};
return index[$0] != undefined ? index[$0] : $0;
});

// "Bye Universe what a beautiful day";

关于javascript - 替换数据 block 中的多个模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2501435/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com