2011-01-25 129 views
1

找到文本#2的正則表達式是什麼? 該模式是它在c之後第一次出現「z =」。我想要的文本是z =後的其餘行。我使用正則表達式在.net簡單的正則表達式搜索

A 
x 
b 
x 
z=text#1 
A 
x 
c 
x 
z=text#2 
+0

A x c b z = text#2上應該發生什麼?或者A x c A z =文本#2? – Axarydax 2011-01-25 08:45:46

回答

2
.*c.*z=([^\n]*).* 

你需要打開.匹配換行符(RegexOptions.SingleLine下文)。

這是一個被My Regex Tester產生了一些C#代碼:(。)

using System; 
using System.Text.RegularExpressions; 
namespace myapp 
{ 
    class Class1 
    { 
     static void Main(string[] args) 
     { 
      String sourcestring = "source string to match with pattern"; 
      Regex re = new Regex(@".*c.*z=([^\n]*).*",RegexOptions.Singleline); 
      MatchCollection mc = re.Matches(sourcestring); 
      int mIdx=0; 
      foreach (Match m in mc) 
      { 
      for (int gIdx = 0; gIdx < m.Groups.Count; gIdx++) 
       { 
       Console.WriteLine("[{0}][{1}] = {2}", mIdx, re.GetGroupNames()[gIdx], m.Groups[gIdx].Value); 
       } 
      mIdx++; 
      } 
     } 
    } 
} 
1

c.+z=(.+)\n

你必須設置正則表達式選項,以便點匹配一切

2

爲了捕捉第一z=whateverc之後,你需要使用一個不情願的量詞:

String source = @"A 
x 
b 
x 
z=text#1 
A 
x 
c 
x 
z=text#2 
A 
x 
d 
x 
z=text#3"; 

Match m = Regex.Match(source, @"c.*?z=([^\n]*)", RegexOptions.Singleline); 
if (m.Success) 
{ 
    Console.WriteLine(m.Groups[1].Value); 
} 

正則表達式在其他答案中給出的最後z=whatever之後的c。由於c之後只有一個z=whatever,所以他們得到了意外的預期結果。

+0

很好的發現,謝謝! – Karsten 2011-01-25 11:40:37