2011-01-25 100 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