Kerberos
Kerberos

Reputation: 1266

Removing part of json string with using REGEX

My json string structure as below

...
}],"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

Upvotes: 1

Views: 1801

Answers (1)

Andrey Korneyev
Andrey Korneyev

Reputation: 26856

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.

Upvotes: 1

Related Questions