Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ssl/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 需要修复一个正则表达式,它替换了太多_C#_Regex_Replace - Fatal编程技术网

C# 需要修复一个正则表达式,它替换了太多

C# 需要修复一个正则表达式,它替换了太多,c#,regex,replace,C#,Regex,Replace,我有这样的字串: Text [City 1 || Location] text [Population] || Text [City 2 || Location] text [Population] 我需要正则表达式,它将[]内的| |替换为== 因此,我必须: Text [City 1 == Location] text [Population] || Text [City 2 == Location] text [Population] 我写了这个正则表达式: str = Regex

我有这样的字串:

Text [City 1 || Location] text [Population] 
|| Text [City 2 || Location] text [Population]
我需要正则表达式,它将[]内的| |替换为==

因此,我必须:

Text [City 1 == Location] text [Population] 
|| Text [City 2 == Location] text [Population]
我写了这个正则表达式:

str = Regex.Replace(str, @"\[(.*?)\|\|(.*?)\]", "[$1==$2]");
但它将所有| |替换为==


如何修复它?

编辑:尝试使用
lookback
lookahead
断言:

(?<= subexpression)
Zero-width positive lookbehind assertion.  

(?= subexpression)
Zero-width positive lookahead assertion. 

(?您应该能够避免匹配所有内容,而只获得如下所示的“| |”:

str = Regex.Replace(str, @"(?<=\[[^\[\]]*)\|\|(?=[^\[\]]*\])", "==");

str=Regex.Replace(str,@)(?谢谢,但是它给出了相同的结果。所有的都被替换了。你能解释为什么这是不同的吗?行!谢谢!你能解释一下这个Regex吗?(?