如何使用Regex提取带续行的文本?

时间:2012-07-19 05:19:20

标签: c# regex

如何使用正则表达式从使用续行符“_”的源字符串中提取以下内容。注意,行继续符必须是该行的最后一个字符。此外,搜索应该从字符串的结尾开始,并在第一个“(”遇到的时候终止。这是因为我只对文本末尾发生的事情感兴趣。

通缉输出:

var1, _
    var2, _
    var3

来源:

...
Func(var1, _
    var2, _
    var3

1 个答案:

答案 0 :(得分:6)

试试这个

(?<=Func\()(?<match>(?:[^\r\n]+_\r\n)+[^\r\n]+)

<强>解释

@"
(?<=             # Assert that the regex below can be matched, with the match ending at this position (positive lookbehind)
   Func             # Match the characters “Func” literally
   \(               # Match the character “(” literally
)
(?<match>        # Match the regular expression below and capture its match into backreference with name “match”
   (?:              # Match the regular expression below
      [^\r\n]          # Match a single character NOT present in the list below
                          # A carriage return character
                          # A line feed character
         +                # Between one and unlimited times, as many times as possible, giving back as needed (greedy)
      _                # Match the character “_” literally
      \r               # Match a carriage return character
      \n               # Match a line feed character
   )+               # Between one and unlimited times, as many times as possible, giving back as needed (greedy)
   [^\r\n]          # Match a single character NOT present in the list below
                       # A carriage return character
                       # A line feed character
      +                # Between one and unlimited times, as many times as possible, giving back as needed (greedy)
)
"