正規表現 +パターンの1つのスペースを含む
質問
次のものに合うようにパターンを書く方法を見つけようとしています:「3Z 5Z」。これの数字は異なる場合がありますが、Zは一定です。私が抱えている問題は、空白を含めようとしていることです...現在、私はこれを私のパターンとして持っています
pattern = @"\b*Z\s*Z\b";
「*」は、「Z」の前の数のワイルドカードを表していますが、そのスペースを使用したくないようです。たとえば、スペースなしで同じものに一致するために、次のパターンを正常に使用できます(つまり、3Z5Z)
pattern = @"\b*Z*Z\b";
私はこのプログラムを.NET 4.0(C#)で執筆しています。どんな助けも大歓迎です!
編集:このパターンは、より大きな文字列の一部です。たとえば、3Z 10Zロック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
"
ところで:
\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();
}
}
}
私は他の投稿に追加され、文字列の開始と終了の文字を追加します。
patter = "^\d+Z\s\d+Z$"
所属していません StackOverflow