1

I have an ASP.NET 4.0 MVC app in C# and I need to create a regex that will match N{3}.N{3}.N{3}.{N{3} where N{3} is any 1, 2, or 3 digits(0-9) e.g.

    1.1.1.1
    111.111.111.111
    1.111.111.1

I have tried

    @"^[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}$"

but this matches things I don't want it to like

    111.1.1
    1111.1.1

What am I doing wrong?

4

2 回答 2

6

.正则表达式中的A表示“任何字符”。因此,如果要匹配文字.,则需要对其进行转义,如下所示:

@"^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$"
于 2013-05-23T20:10:44.353 回答
1

如果您尝试匹配 IP 地址,这里有一些很棒的 RexEx 表达式:

匹配 DNS 主机名或 IP 地址的正则表达式?

于 2013-05-23T20:42:15.140 回答