正则表达式+包括模式中的一个空格

时间:2011-12-01 18:50:12

标签: c# arrays regex function output

我正在试图弄清楚如何编写一个模式以匹配以下内容:“3Z 5Z”。这里的数字可能会有所不同,但Z是不变的。我遇到的问题是试图包含空格...目前我将此作为我的模式

 pattern = @"\b*Z\s*Z\b";

'*'表示“Z”之前的数字的通配符,但它似乎不想使用其中的空格。例如,我可以成功使用以下模式匹配同一个没有空格的东西(即3Z5Z)

pattern = @"\b*Z*Z\b";

我在.NET 4.0(C#)中编写这个程序。非常感谢任何帮助!

编辑:此模式是较大字符串的一部分,例如: 3Z 10Z锁425“

3 个答案:

答案 0 :(得分:4)

试试这个:

pattern = @"\b\d+Z\s+\d+Z\b";

<强>解释

"
\b    # Assert position at a word boundary
\d    # Match a single digit 0..9
   +     # Between one and unlimited times, as many times as possible, giving back as needed (greedy)
Z     # Match the character “Z” literally
\s    # Match a single character that is a “whitespace character” (spaces, tabs, line breaks, etc.)
   +     # Between one and unlimited times, as many times as possible, giving back as needed (greedy)
\d    # Match a single digit 0..9
   +     # Between one and unlimited times, as many times as possible, giving back as needed (greedy)
Z     # Match the character “Z” literally
\b    # Assert position at a word boundary
"

顺便说一下:

\b*

应抛出异常。 \b是一个词锚。你不能量化它。

答案 1 :(得分:1)

试试这段代码。

using System;
using System.Text.RegularExpressions;

namespace ConsoleApplication1
{
  class Program
  {
    static void Main(string[] args)
    {
      string txt="3Z 5Z";

      string re1="(\\d+)";  // Integer Number 1
      string re2="(Z)"; // Any Single Character 1
      string re3="( )"; // Any Single Character 2
      string re4="(\\d+)";  // Integer Number 2
      string re5="(Z)"; // Any Single Character 3

      Regex r = new Regex(re1+re2+re3+re4+re5,RegexOptions.IgnoreCase|RegexOptions.Singleline);
      Match m = r.Match(txt);
      if (m.Success)
      {
            String int1=m.Groups[1].ToString();
            String c1=m.Groups[2].ToString();
            String c2=m.Groups[3].ToString();
            String int2=m.Groups[4].ToString();
            String c3=m.Groups[5].ToString();
            Console.Write("("+int1.ToString()+")"+"("+c1.ToString()+")"+"("+c2.ToString()+")"+"("+int2.ToString()+")"+"("+c3.ToString()+")"+"\n");
      }
      Console.ReadLine();
    }
  }
}

答案 2 :(得分:1)

除了其他帖子,我还会添加字符串Begin和End的字符。

patter = "^\d+Z\s\d+Z$"