开发者

Probably simple regex search

What is the regex to fin开发者_StackOverflow中文版d text#2? The pattern is that it's the first occurance of "z=" after c. The text I want is the rest of the line after z=. I'm using the regex in .Net

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


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

You'll need to turn on . matching newlines (RegexOptions.SingleLine below).

Here's some C# code generated by My Regex Tester:

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++;
          }
        }
    }
}


To capture the first z=whatever after the c, you need to use a reluctant quantifier:

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);
}

The regexes given in the other answers capture the last z=whatever after the c. Since there's only the one z=whatever after the c, they get the expected result by accident.


c.+z=(.+)\n

You'd have to set regex options so dot (.) matches everything

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜