Question

Je suis en train de comprendre comment écrire un modèle pour correspondre à ce qui suit: « 3Z 5Z ». Les chiffres de ce peuvent varier, mais les années Z sont constants. La question que j'ai essaie d'inclure l'espace blanc ... Actuellement, je suis ce que mon modèle

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

Le « * » représentent le caractère générique pour le numéro précédent de la « Z », mais il ne semble pas vouloir travailler avec l'espace en elle. Par exemple, je peux utiliser le modèle suivant avec succès pour la correspondance à la même chose sans l'espace (à savoir 3Z5Z)

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

Je suis en train d'écrire ce programme en .NET 4.0 (C #). Toute aide est très appréciée!

EDIT: Ce modèle fait partie d'une chaîne plus grande, par exemple: 3Z 10Z verrouillage 425"

Était-ce utile?

La solution

Essayez ceci:

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

Explication:

"
\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
"

Par ailleurs:

\b*

devrait lancer une exception. \b est un point d'ancrage de texte. Vous ne pouvez pas quantifier.

Autres conseils

Essayez ce code.

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

Je ainsi que d'autres messages j'ajouter des caractères de Begin et de fin de chaîne.

patter = "^\d+Z\s\d+Z$"
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top