简体   繁体   English

使用REGEX删除部分json字符串

[英]Removing part of json string with using REGEX

My json string structure as below 我的json字符串结构如下

...
}],"twitter":[{"id": .... blaa"}]}
...

I am trying to remove this part as below 我正在尝试如下删除此部分

Regex.Replace(_VarJson, string.Format("{0}.*?{1}", "\"twitter\":[{", "\"}]"), string.Empty)

But nothing removes. 但是什么也不能消除。 Where is my wrong? 我哪里错了?

Thank you in advance 先感谢您

In your regex pattern [{}] symbols should be escaped with \\ symbol since they are reserved regex symbols ( [] stands for charactrers group and {} stands for repetitions count). 在您的正则表达式模式中, [{}]符号应使用\\符号转义,因为它们是保留的正则表达式符号( []代表字符组, {}代表重复计数)。

So your replacement could be done as 所以你的替换可以完成

_VarJson = Regex.Replace(_VarJson, 
    string.Format("{0}.*?{1}", 
    "\"twitter\":\\[\\{", "\"\\}\\]"), 
    string.Empty);

But I strongly agreed with opinion of @CommuSoft posted in comments - it's better to use some JSON library to parse your source JSON, then remove all you need from object model and write back JSON as text if needed. 但是我强烈同意@CommuSoft在评论中发布的观点-最好使用一些JSON库来解析源JSON,然后从对象模型中删除所有需要的内容,并在需要时将JSON作为文本写回。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM