digiogi
digiogi

Reputation: 270

Regular expression to change string between curly brackets

I have a file and I want to change text inside it with regex.

"code": {
  "restore": 1,
  "restore_on_startup": true,
},

I want to change the text between

"code": {

and

},

I tried something like

Regex.Replace(subject, @"?xxx.*?yyy", "Replace");

But as my text contains new lines, it didn't work.

Upvotes: 0

Views: 1265

Answers (3)

Jason
Jason

Reputation: 3960

This regex should work for your seample, it will replace everything inside the brackets

Regex.Replace(subject,"(?<=\"code\":\\s{).*?(?=},)", "replace", RegexOptions.Singleline);

"code": { "restore": 1, "restore_on_startup": true, },

will yield

"code": {replace},

The regex is basically saying match everything that is prefixed with "code": { and is suffixed with }, then replace everything inside with my replace. You may need to tweak it to suit your needs.

Upvotes: 1

Viktor Pless
Viktor Pless

Reputation: 161

use

(.|\\r|\\n)*? 

instead of

.*?

or use the multiline property in the RegexOptions class

Upvotes: 1

Daniel M&#246;ller
Daniel M&#246;ller

Reputation: 86600

I'd suggest you go line by line searching for "code": {.

That found, from the same line start looking for }. (Beware to look after the code part in the first line, because there may be a } before the code)

Go storing all lines with a List<string> Add until you find the }.

After that, concat all lines you found in a single string, do the replacement. Remove all those lines from file and add the new formed string.

Upvotes: 0

Related Questions