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.
use
(.|\\r|\\n)*?
instead of
.*?
or use the multiline property in the RegexOptions class
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.