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吗?(?