4

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

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

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

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

我正在用 .NET 4.0 (C#) 编写这个程序。任何帮助深表感谢!

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

4

3 回答 3

5

试试这个:

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是一个词锚。你无法量化它。

于 2011-12-01T18:51:55.387 回答
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();
    }
  }
}
于 2011-12-01T18:54:51.867 回答
1

除了其他帖子之外,我还会添加字符串开头和结尾的字符。

patter = "^\d+Z\s\d+Z$"
于 2011-12-01T18:59:40.957 回答