[英]Replacing multiple patterns in a block of data
我需要找到在單個文本塊上匹配多個正則表達式的最有效方法。 舉一個我需要的例子,考慮一個文本塊:
“你好世界,多么美好的一天”
我想用“再見”代替“Hello”,用“宇宙”代替“世界”。 我總是可以在循環中做到這一點,使用各種語言中可用的 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 [/([AZ])/, $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";
您可以傳遞一個函數來替換:
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";
改進的答案:
var index = {
'Hello': 'Bye',
'World': 'Universe'
};
var pattern = '';
for (var i in index) {
if (pattern != '') pattern += '|';
pattern += i;
}
var text = "Hello World what a beautiful day";
text.replace(new RegExp(pattern, 'g'), function($0) {
return index[$0] != undefined ? index[$0] : $0;
});
如果問題是如何用相應的替換( 字符串或函數)替換多個通用模式,由於特殊字符、捕獲組和反向引用匹配,這將非常棘手。
您可以將https://www.npmjs.com/package/union-replacer用於此確切目的。 它基本上是一個string.replace(regexp, string|function)
對應物,它允許在一次傳遞中進行多次替換,同時保留string.replace(...)
。
披露:我是作者,開發該庫是因為我們必須支持用戶配置的替換。
涉及替換許多模式的常見任務是使用戶或其他字符串在 Web 頁面上呈現“安全”,這意味着阻止 HTML 標記處於活動狀態。 這可以在 JavaScript 中使用 HTML 實體和 forEach 函數完成,允許一組異常(即允許呈現的一組 HTML 標記)。
這是一項常見任務,以下是完成它的一種相當簡短的方法:
// Make a string safe for rendering or storing on a Web page
function SafeHTML(str)
{
// Make all HTML tags safe
let s=str.replace(/</gi,'<');
// Allow certain safe tags to be rendered
['br','strong'].forEach(item=>
{
let p=new RegExp('<(/?)'+item+'>','gi');
s=s.replace(p,'<$1'+item+'>');
});
return s;
} // SafeHTML
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.