【问题标题】:remove substring between delimiters FROM LEFT TO RIGHT using regex - C#使用正则表达式从左到右删除分隔符之间的子字符串 - C#
【发布时间】:2023-03-28 22:59:01
【问题描述】:

我正在尝试使用正则表达式从字符串中从左到右删除子字符串,这意味着我希望识别正确的分隔符,然后删除所有内容,直到在左侧找到最接近的分隔符(而不是其他方式左右分隔符不同)。

一个例子:

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 ]] "

非常感谢您的帮助!

【问题讨论】:

    标签: c# regex


    【解决方案1】:

    使用否定而不是.* 标记。此外,将您的模式放在逐字字符串文字中。

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

    Ideone Demo

    【讨论】:

      【解决方案2】:

      使用此代码,我添加了一个否定字符类,以确保我们不会在双 [ 之后捕获 [

       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

      【讨论】:

        【解决方案3】:

        您需要使用否定的前瞻断言。

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

        DEMO

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2010-11-24
          • 1970-01-01
          • 2014-04-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-05-13
          相关资源
          最近更新 更多