正则表达式删除json属性 [英] Regex remove json property

查看:208
本文介绍了正则表达式删除json属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想根据它的密钥删除一个字符串的json属性,无论它的值类型是什么。但是只有当它的值是一个字符串并且它在对象的根级别上时才会删除它,这对于开始是很好的。我试过这个:

I'd like to remove a stringfied json's property based on its key wherever it is, whatever its value type is. But removing it only if its value is a string and its on the root level of the object would be nice for a beggining. I tried this:

[,]{1}[\s]*?\"attrName\"[ ]*?[:][ ]*?\".*\"[^,]|\"attrName\"[ ]*?[:][ ]*?\".*\"[,]{0,1}

示例: https://regex101.com/r/PAlqYi/1

但它看起来很多如果attrName是第一个属性,最后一个在json三个中间的东西,那么它确实会删除逗号。有没有人有更好的想法让这个正则表达式更具可读性?

but it looks a lot big to do such a simple job, what it does is ensure the comma will be removed as well, if attrName is the first attribute, the last ot something in the middle of the json three. Does anyone has a better idea to make this regex more readable?

推荐答案

如果你有任何使用解析器的方法,那就更多了稳定可读的解决方案。正则表达式 \ * * \attr \*:* \。* \(,|(?= \s + \}))应该更短更好。

If you have any way of using a parser it's a more stable and readable solution. The regex \s*\"attr\" *: *\".*\"(,|(?=\s+\})) should be shorter and better.

示例

我做了一些帮助改变:


  1. 不要使用如此多的字符类,如 [,] 。如果字符类中只有一个元素,则它应该单独保留。

  2. 仅在需要时使用编号计数。例如: {0,1} {1} 没有意义。

  3. 而不是在上一行中搜索逗号,看它是否是列表的结尾,检查是否有} 后面的行允许您将条件组合在一起。

  4. 最后使用正向前瞻来搜索} ,以便在替换期间不会删除它。

  1. Don't use so many character classes like [,]. If there is only one element in a character class it should be left by itself.
  2. Only use numbered counts when required. Ex: {0,1} is ? and {1} is pointless.
  3. Instead of searching for a comma in the previous line to see if it is the end of a list checking if there is a } following the line allows you to group the conditionals together.
  4. A positive lookahead is used at the end to search for } so it wouldn't be removed during the substitution.

这篇关于正则表达式删除json属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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