在一个数据块替换多个图案多个、在一、图案、数据

由网友(可遇不可求)分享简介:我需要找到一个单独的文字块匹配多个定期EX pressions的最有效的方式。为了给什么,我需要一个例子,考虑文本块:I need to find the most efficient way of matching multiple regular expressions on a single block of...

我需要找到一个单独的文字块匹配多个定期EX pressions的最有效的方式。为了给什么,我需要一个例子,考虑文本块:

I need to find the most efficient way of matching multiple regular expressions on a single block of text. To give an example of what I need, consider a block of text:

你好世界多么美好的一天

"Hello World what a beautiful day"

我想用再见和世界与宇宙替代你好。我可以使用类似与string.replace功能availiable各种语言总是这样做在一个循环ofcourse。

I want to replace Hello with "Bye" and "World" with Universe. I can always do this in a loop ofcourse, using something like String.replace functions availiable in various languages.

不过,我可以有文字多个字符串模式,我需要匹配,更换一块巨大。

However, I could have a huge block of text with multiple string patterns, that I need to match and replace.

我在想,如果我可以使用普通防爆pressions有效地做到这一点还是我必须使用像LALR解析器。

I was wondering if I can use Regular Expressions to do this efficiently or do I have to use a Parser like LALR.

我需要这样做的JavaScript,因此如果任何人知道,可以把它做的工具,这将是AP preciated。

I need to do this in JavaScript, so if anyone knows tools that can get it done, it would be appreciated.

推荐答案

您可以通过一个函数来代替:

You can pass a function to replace:

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";
阅读全文

相关推荐

最新文章