0

我很茫然,我需要一些帮助。

字符串看起来像:

"Hello World

@start some text @end

@start more text @end"

我需要一个正则表达式模式,它将匹配从@start第一个到第一个@end。在此示例中,我们将有两个匹配项 ( @start (some text) @end)。@ 标签内的文本可以包含换行符。

有任何想法吗?

4

2 回答 2

1

这段代码:

string s = "Hello world\n@start text1 @end\n@start text2 @end";
Regex r = new Regex(@"(?<=@start)[\s\S]*?(?=@end)");
var mm = r.Matches(s);

制作了2场比赛。

诀窍是:

  • 使用非贪婪匹配(*?而不是 just *
  • 用于[\s\S]匹配任何字符,包括换行符
  • 使用前瞻/后瞻 ( (?...))
于 2012-06-13T16:56:58.290 回答
0

编辑:(得到*?向后。修复它。)

(?<=@start).*?(?=@end)

编辑:哎呀,做那个单行

“。” 默认情况下不会匹配换行符,但您可以启用它。如何做到这一点取决于您使用的正则表达式引擎,但通常称为“单行”

编辑:看到您正在使用.NET。试试这个:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace RegexSandboxCSharp {
  class Program {
    static void Main(string[] args) {

      string l_input = @"Hello World  

@start some text @end  

@start more text @end";


      // This is the relevant piece of code:    
      MatchCollection l_matches = Regex.Matches( l_input, "(?<=@start).*?(?=@end)", RegexOptions.Singleline );



      foreach ( Match l_match in l_matches ) {
        Console.WriteLine( l_match.Value );
      }

      Console.ReadKey( true );

    }
  }
}
于 2012-06-13T16:53:48.290 回答