正则表达式以特定字符开头的行块?

时间:2013-05-05 10:53:07

标签: c# .net regex

问题:

给出以下文本文件:

blablabla
# Block 1
# Some text
## Some more text
### Even more text
### Hello
# Some text
### Again Text
# Blank lines or lines not starting with # terminate

blablabala
# Block 1
# Some text
## Some more text
### Even more text
### Hello
# Some text
### Again Text
# Blank lines or lines not starting with # terminate
blablabla

是否可以使用正则表达式提取以#开头的所有行块? 注意:
该块应该是一个字符串,只需提取以#开头的所有行是微不足道的。

其他问题:
是否可以在正则表达式中获得前导#的数量?

2 个答案:

答案 0 :(得分:1)

使用

var regex = new Regex(@"(#.*([\n]|$))+");
var matches = regex.Matches(sample_string);
sample_string设置为您的示例的

将返回两个匹配项,第一个块为matches[0],第二个块为matches[1]

答案 1 :(得分:0)

  Regex RE = new Regex(@"\n+#.*", RegexOptions.Multiline);
  MatchCollection theMatches = RE.Matches(text);
  theMatches.Count; //gives number of matches

我使用regex.com来测试我的正则表达式是否正常工作。

 string str = @"blablabla
                # Block 1
                # Some text
                ## Some more text
                ### Even more text
                ### Hello
                # Some text
                ### Again Text
                # Blank lines or lines not starting with # terminate";
        Regex RE = new Regex(@"\n+#.*", RegexOptions.Multiline);
        MatchCollection theMatches = RE.Matches(str);
        theMatches.Count.ToString();
         foreach (Match match in theMatches)
         {
                 Console.WriteLine(match.ToString());
         }

out put是

'#Block 1

'#some text

'##更多文字

'###更多文字

'### Hello

'#some text

'### Again Text

'#空行或行不以#terminate

开头