1

私は非常に単純な正規表現を書こうとしています - この世界は私にとってまったく新しいものなので、助けが必要です.

次のパターンを検証する必要があります。たとえば、C0 で始まり、正確に 4 桁で終わります。

C01245 - legal

C04751 - legal

C15821 - not legal (does not starts with 'C0')

C0412 - not legal (mismatch length)

C0a457 - not legal 

私は「チートシート」を取り、次のパターンを書きました:

C0\A\d{4) つまり (私が思うに) : C0 で始まり、4 桁で続きますが、このパターンは常に "false" を返します。

私のパターンのどこが悪いのですか?

4

4 に答える 4

1
^C0\d{4,}$

文字列は で始まり^、文字列の最後にC04 桁以上の数字が続く必要があります。\d{4,}$

$実際に文字列の最後にない場合は、単に最後を外してください。

さらに数字を挟む必要がない場合は、カンマを削除してください。

@femtoRgon への称賛\d{4,}(コメントを参照)。

于 2013-07-03T04:34:22.580 に答える
0

このスニペットをご覧ください。

using System.IO;
using System;
using System.Text.RegularExpressions;

class Program
{
    static void Main()
    {
        string input1 = "C0123456"; 
        // input1 starts with C0 and ends with 4 digit , allowing any number of                 
        // characters/digit in between
        string input2 = "C01234";
        // input2 starts with C0 and ends with 4 digit , without                
        // characters/digit in between
        String pattern1=@"\b[C][0][a-z A-Z 0-9]*\d{4}\b";
        String pattern2=@"\b[C][0]\d{4}\b";
        Match m = Regex.Match(input1, pattern1);
        if(m.Success)
        Console.WriteLine("Pattern1 matched input1 and the value is : "+m.Value);
        m = Regex.Match(input2, pattern2);
        if(m.Success)
        Console.WriteLine("Pattern2 matched input2 and the value is : "+m.Value);
          m = Regex.Match(input1, pattern2);
        if(m.Success)
        Console.WriteLine("Pattern2 matched input1 and the value is : "+m.Value);
          m = Regex.Match(input2, pattern1);
        if(m.Success)
        Console.WriteLine("Pattern1 matched input2 and the value is : "+m.Value);


    }
}

出力:

パターン 1 は入力 1 と一致し、値は次のとおりです: C0123456

パターン 2 は入力 2 と一致し、値は次のとおりです: C01234

パターン 1 は入力 2 と一致し、値は次のとおりです: C01234

于 2013-07-03T05:25:24.547 に答える
-1

http://gskinner.com/RegExr/にアクセスすると、次の式を記述できます。

^(C0[0-9]*[0-9]{4})[^0-9]

そして、あなたが入れたコンテンツで:

C012345 - legal
C047851 - legal
C*1*54821 - not legal (does not starts with 'C0')
C0412 - not legal (mismatch length)
C0*a*4587 - not legal

そして、それがあなたが望むものだけに一致することがわかります.

于 2013-07-03T04:34:21.853 に答える