[英]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. 但由于我的文字包含新行,因此无效。
use 采用
(.|\\r|\\n)*?
instead of 代替
.*?
or use the multiline property in the RegexOptions class 或使用RegexOptions类中的multiline属性
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, }, “code”:{“restore”:1,“restore_on_startup”:true,},
will yield 会屈服
"code": {replace}, “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 . 正则表达式基本上是匹配以
"code": {
为前缀的所有内容"code": {
并且后缀为},
然后用我的替换替换内部的所有内容。 You may need to tweak it to suit your needs. 您可能需要调整它以满足您的需求。
I'd suggest you go line by line searching for "code": {
. 我建议你逐行搜索
"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
) (注意在第一行中查看
code
部分,因为在code
之前可能有}
Go storing all lines with a List<string> Add
until you find the }
. 使用
List<string> Add
存储所有行,直到找到}
。
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.
从文件中删除所有这些行并添加新形成的字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.