开发者

Regular expressions C# (xxxx-xxxx mask)

开发者 https://www.devze.com 2023-02-06 21:55 出处:网络
I can not understand how to make regular expression For example I have mask: xxxx-xxxx-xxxx where \"x\" can be a-z or A-Z or 0-9

I can not understand how to make regular expression For example I have mask: xxxx-xxxx-xxxx where "x" can be a-z or A-Z or 0-9

And have code:

            string[] numbers = 
                 {
                     "1a3F-5t5C-FIG0-InFo", 
                     "444-234-2245", 
                     "444.-2344-2245", 
                 };
        string sPattern = "^[a-z0-9A-z]{4}-[a-z0-9A-z]{4}-[a-z0-9A-z]{4}$-[a-z0-9A-z]{4}$";
        var validList = new List<开发者_StackOverflow中文版;string>();

        foreach (string s in numbers)
        {
            if (Regex.IsMatch(s, sPattern))
            {
                validList.Add(s);
            }
        }
        Assert.IsTrue(validList.Count==1);

But it doesn't work... I have some mistakes in expression. Could you explain why is it wrong?


Two things spring to mind: "a-z0-9A-z" should be "a-z0-9A-Z" (note the capital Z), and you've got a $ in the middle of the expression which shouldn't be there. It looks like your mask is currently trying to match four sets of xxxx rather than three, too.

Try fixing those three things and then update the question if you're still having problems.

Personally I would create an instance of Regex for the pattern, btw:

Regex regex = new Regex(
    "^[a-z0-9A-Z]{4}-[a-z0-9A-Z]{4}-[a-z0-9A-Z]{4}$");


You may want to look into using named grouping (?<name>.*) which goes great with multiple subsections ((?<str>[^-]+)-?)+.

Also http://txt2re.com/ may be helpful.

(Note: Not an answer, just some (hopefully) helpfull additional info.)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号