Regex remove json property

狂风中的少年 提交于 2019-12-14 00:28:34

问题


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}

Example : https://regex101.com/r/PAlqYi/1

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?


回答1:


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.

Example

Several changes I made to help:

  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.



回答2:


I modified the regex from the first example, it works better even if is Flat JSON

\s*\"attr\" *: *(\"(.*?)\"(,|\s|)|\s*\{(.*?)\}(,|\s|))

Example



来源:https://stackoverflow.com/questions/46160681/regex-remove-json-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!