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

本文关键字:空格 包含一 模式 正则表达式 | 更新日期: 2023-09-27 18:16:28

我正试图找出如何编写一个模式来匹配以下内容:"3Z 5Z"。这里的数字可以变化,但Z是恒定的。我遇到的问题是试图包括空白…目前我的模式是

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

"*"表示"Z"前面的数字的通配符,但它似乎不想与其中的空格一起工作。例如,我可以成功地使用以下模式来匹配没有空格(即3Z5Z)

的相同内容
pattern = @"'b*Z*Z'b";

我正在用。net 4.0 (c#)编写这个程序。任何帮助都非常感激!

编辑:这个模式是一个更大字符串的一部分,例如:3z10z锁定425"

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

试试这个:

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
"

By the way:

'b*

应该抛出异常。'b是一个词锚。你无法量化它

试试这段代码。

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

如果在其他帖子中添加Begin和End字符,

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