多个正则表达式替换

编程入门 行业动态 更新时间:2024-10-10 01:26:27
本文介绍了多个正则表达式替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我对正则表达式感到困惑我认为当涉及到这些可怕的代码时,我会有阅读困难..无论如何,必须有一种更简单的方法来做到这一点 - (即在一行中列出一组替换实例) , 任何人?在此先感谢。

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.

更多推荐

多个正则表达式替换

本文发布于:2023-06-11 03:31:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/625727.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   正则表达式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!