替换数据块中的多个模式

Vik*_*ntY 9 javascript regex algorithm

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

"Hello World多么美好的一天"

我想用Universe替换Hello与"Bye"和"World".我总是可以在一个循环的循环中使用像各种语言中可用的String.replace函数这样的东西.

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

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

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

mač*_*ček 14

编辑

在我原来的答案(下面)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"
Run Code Online (Sandbox Code Playgroud)

与之前的答案相比,这具有巨大的优势,需要您每次写两次比赛.它还可以让您个人控制每场比赛.例如:

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"
Run Code Online (Sandbox Code Playgroud)


原始答案

可以修改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";
Run Code Online (Sandbox Code Playgroud)

  • 可能你不应该为每次调用替换函数重新创建查找对象,对吧,而是把它放在外面? (2认同)

And*_*y E 11

您可以传递一个函数来替换:

var hello = "Hello World what a beautiful day";
hello.replace(/Hello|World/g, function ($0, $1, $2) // $3, $4... $n for captures
{
    if ($0 == "Hello")
        return "Bye";
    else if ($0 == "World")
        return "Universe";
});

// Output: "Bye Universe what a beautiful day";
Run Code Online (Sandbox Code Playgroud)