0

私は途方に暮れています、助けが必要です。

文字列は次のようになります。

"Hello World

@start some text @end

@start more text @end"

@startから最初の までのすべてに一致する正規表現パターンが必要@endです。この例では、2 つの一致があります ( @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 に答える