Javascript 多个正则表达式替换
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4285472/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Multiple Regex replace
提问by Inigo
I am boggled by regex I think I'm dyslexic when it comes to these horrible bits of code.. anyway, there must be an easier way to do this- (ie. list a set of replace instances in one line), anyone? Thanks in advance.
我对正则表达式感到困惑我认为当谈到这些可怕的代码时我有阅读障碍..无论如何,必须有一种更简单的方法来做到这一点 - (即在一行中列出一组替换实例),有人吗?提前致谢。
function clean(string) {
string = string.replace(/\@~rb~@/g, '').replace(/}/g, '@~rb~@');
string = string.replace(/\@~lb~@/g, '').replace(/{/g, '@~lb~@');
string = string.replace(/\@~qu~@/g, '').replace(/\"/g, '@~qu~@');
string = string.replace(/\@~cn~@/g, '').replace(/\:/g, '@~cn~@');
string = string.replace(/\@-cm-@/g, '').replace(/\,/g, '@-cm-@');
return string;
}
采纳答案by fifigyuri
You can define either a generic function, which would make sense if you can reuse it in more parts of your code, thus making it DRY. If you don't have reason to define a generic one, I would compress only the part which cleans sequences and leave the other replaces as they are.
您可以定义一个泛型函数,如果您可以在代码的更多部分中重用它,这将是有意义的,从而使其成为 DRY。如果你没有理由定义一个通用的,我只会压缩清理序列的部分,而让其他替换保持原样。
function clean(string) {
string = string.replace(/\@~rb~@|\@~lb~@|\@~qu~@|\@~cn~@|\@-cm-@/g, '')
.replace(/}/g, '@~rb~@').replace(/{/g, '@~lb~@')
.replace(/\"/g, '@~qu~@').replace(/\:/g, '@~cn~@')
.replace(/\,/g, '@-cm-@');
return string;
}
But be careful, the order of the replacements were changed it in this code.. although it seemsthey might not affect the result.
但要小心,替换的顺序在这段代码中被改变了......虽然看起来它们可能不会影响结果。
回答by Markus Jarderot
You could use a function replacement. For each match, the function decides what it should be replaced with.
您可以使用函数替换。对于每个匹配项,该函数决定应该用什么来替换它。
function clean(string) {
// All your regexps combined into one:
var re = /@(~lb~|~rb~|~qu~|~cn~|-cm-)@|([{}":,])/g;
return string.replace(re, function(match,tag,char) {
// The arguments are:
// 1: The whole match (string)
// 2..n+1: The captures (string or undefined)
// n+2: Starting position of match (0 = start)
// n+3: The subject string.
// (n = number of capture groups)
if (tag !== undefined) {
// We matched a tag. Replace with an empty string
return "";
}
// Otherwise we matched a char. Replace with corresponding tag.
switch (char) {
case '{': return "@~lb~@";
case '}': return "@~rb~@";
case '"': return "@~qu~@";
case ':': return "@~cn~@";
case ',': return "@-cm-@";
}
});
}
回答by jwueller
You could do it like this:
你可以这样做:
function clean(str) {
var expressions = {
'@~rb~@': '',
'}': '@~rb~@',
// ...
};
for (var key in expressions) {
if (expressions.hasOwnProperty(key)) {
str = str.replace(new RegExp(key, 'g'), expressions[key]);
}
}
return str;
}
Keep in mind that the order of object properties is not reliably determinable (but most implementations will return them in order of definition). You will probably need multiple constructs like this if you need to ensure a specific order.
请记住,对象属性的顺序无法可靠地确定(但大多数实现将按照定义的顺序返回它们)。如果您需要确保特定顺序,您可能需要多个这样的构造。
回答by Stephen
You can just chain them all in order.
您可以按顺序将它们全部链接起来。
function clean(string) {
return string.replace(/\@~rb~@/g, '').replace(/}/g, '@~rb~@')
.replace(/\@~lb~@/g, '').replace(/{/g, '@~lb~@')
.replace(/\@~qu~@/g, '').replace(/\"/g, '@~qu~@')
.replace(/\@~cn~@/g, '').replace(/\:/g, '@~cn~@')
.replace(/\@-cm-@/g, '').replace(/\,/g, '@-cm-@');
}
回答by Jonny Buchanan
...there must be an easier way to do this- (ie. list a set of replace instances in one line)...
...必须有一种更简单的方法来做到这一点-(即在一行中列出一组替换实例)...
Yum, API-first thinking. How about...?
嗯,API 优先的想法。怎么样...?
var clean = multiReplacer({
"@~rb~@": "",
"@~lb~@": "",
"@~qu~@": "",
"@~cn~@": "",
"@-cm-@": "",
"}": "@~rb~@",
"{": "@~lb~@",
"\": "@~qu~@",
":": "@~cn~@",
",": "@-cm-@"
});
Plumbing:
水暖:
// From http://simonwillison.net/2006/Jan/20/escape/
RegExp.escape = function(text)
{
return text.replace(/[-[\]{}()*+?.,\^$|#\s]/g, "\$&");
};
function multiReplacer(replacements)
{
var regExpParts = [];
for (prop in replacements)
{
if (replacements.hasOwnProperty(prop))
{
regExpParts.push(RegExp.escape(prop));
}
}
var regExp = new RegExp(regExpParts.join("|"), 'g');
var replacer = function(match)
{
return replacements[match];
};
return function(text)
{
return text.replace(regExp, replacer);
};
}