C#Regex替换自定义json路径

时间:2015-09-11 18:11:28

标签: c# regex

我有一个这样的字符串:

Books[?(@.Author=='auth1 or auth2' or @.Author=='auth3 or auth4' or @.Author=='auth5 or auth6')].Revision

我需要使用Regex.Replace:

输出如下
Books[?(@.Author=='auth1 or auth2' || @.Author=='auth3 or auth4' || @.Author=='auth5 or auth6')].Revision

我尝试使用Regex.Replace(string, @"(?<filter>@\..*) or @", "${filter} || @")。但输出如下:

Books[?(@.Author=='auth1 or auth2' or @.Author=='auth3 or auth4' ||
 @.Author=='auth5 or auth6')].Revision

1 个答案:

答案 0 :(得分:1)

我应该使用积极的先行断言。

Regex.Replace(string, @" or(?=\s+@\.)", " ||");

Regex.Replace(string, @" or(?=\s+@\.Author==')", " ||");

(?=...)称为正向前瞻,断言匹配必须后跟

\s+一个或多个空格

@. @和一个点。