2015-04-07 33 views
1

我想使用正则表达式从字符串中删除一个子字符串,从左到右,这意味着我想要正确的分隔符被识别,然后删除一切,直到在左侧找到最接近的分隔符(而不是相反的方向,左右分隔符不同)。删除分隔符之间的子字符串从左到右使用正则表达式C#

一个例子:

string myInput = "This [[ should stay and [[ this sould go | this should stay ]] as well"; 
string myRegex = "\\[\\[(.*?)\\|"; 
string myOutput = Regex.Replace (myInput, myRegex,""); 

我想从去除一切 “|”到第一个“[[”在左边,但正则表达式从第一个“[[”在句子中直到“|”)。

I get: myOutput = "This this should stay ]] as well" 

When what I really want is: "This [[ should stay and this should stay ]] " 

非常感谢!

回答

0

使用否定而不是.*令牌。另外,将你的模式放在逐字字符串文字中。

string myRegex = @"\[\[[^[|]*\|"; 

Ideone Demo

0

您需要使用否定性预测声明。

myOutput = Regex.Replace(myInput, @"\[\[(?:(?!\[\[).)*?\|", ""); 

DEMO

(?:(?!\[\[).)*?会匹配任何字符但不是[[非贪婪。也就是说,这将检查将要匹配的字符将不是[[中的第一个字符的条件。如果是,那么它将匹配相应的字符,否则匹配将失败,因为实际上遵循负向前瞻的模式是\|匹配文字管道符号),其期望紧接着的管道符号。

0

使用此代码,我添加了一个否定的字符类,将确保我们没有捕捉到[后双[

string myInput = "This [[ should stay and [[ this sould go | this should stay ]] as well"; 
string myRegex = @"\[\[([^\[]*?)\|"; 
string myOutput = Regex.Replace(myInput, myRegex, ""); 

输出:

This [[ should stay and this should stay ]] as well 

看看sample program

相关问题