多个正则表达式替换 [英] Multiple Regex replace
问题描述
我对正则表达式感到困惑我认为当涉及到这些可怕的代码时,我会有阅读困难..无论如何,必须有一种更简单的方法来做到这一点 - (即在一行中列出一组替换实例) , 任何人?在此先感谢。
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;
}
推荐答案
您可以定义一个通用函数,如果您可以在更多部分重用它,这将是有意义的你的代码是干的。如果你没有理由定义一个通用的代码,我只会压缩清除序列的部分,并保留其他部分替换它们。
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.
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 seems they might not affect the result.
这篇关于多个正则表达式替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!