在一个数据块替换多个图案 [英] Replacing multiple patterns in a block of data

查看:106
本文介绍了在一个数据块替换多个图案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要找到一个单独的文字块匹配多个定期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";

这篇关于在一个数据块替换多个图案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆