c# - 伪 IPv4 正则表达式

标签 c# regex

假设最大IP可以包含每个“点”括号中的最大数量999,即999.999.999.999 是最大的可用值。
我已经在计算器中检查了正则表达式 ([0-9]+.){3}[0-9]。那么,为什么程序抛出运行时错误“parsing "?([0-9]+.){3}[0-9]"- Quantifier {x,y} following nothing."?

using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace RegExCs
{
    class Program
    {
        static void Main(string[] args)
        {
            string rawData;
            Regex filter = new Regex(@"?<ip>([0-9]+\.){3}[0-9]"); //run-time error 

            rawData=File.ReadAllText("Query list");

            MatchCollection theMatches = filter.Matches(rawData);

            foreach (Match theMatch in theMatches)
            {
                Console.WriteLine("ip: {0}\n",theMatch.Groups["ip"]);
            }


            Console.ReadKey();

        }
    }
}

Official help page 对我帮助不大。

“查询列表”文件内容:

Reply from 212.77.100.101 www.wp.pl time: 21:37
Reply from 111.41.130.55 www.dupa.pl time: 05:33
Reply from 230.77.100.101 www.whatanannoyingbug.com time: 04:12
Reply from 65.77.100.101 www.foooo.org time: 12:55
Reply from 200.77.100.101 www.example.com time: 07:56

最佳答案

您需要用括号将整个正则表达式括起来,更改 ?<ip>([0-9]+\.){3}[0-9]到以下内容:

(?<ip>([0-9]+\.){3}[0-9])

这是必要的,因为 ?<name>创建命名组的语法仅在紧跟在左括号之后有效,否则 ?意思是“使前一个元素可选”。由于 ? 之前没有前一个元素, 你收到一个错误。

关于c# - 伪 IPv4 正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10905936/

相关文章:

regex - AWK - 基于正则表达式添加值

C#:自定义转换为值类型

c# - 防止 ASP.Net 项目将 {assembly}.dll.config 复制到 bin 文件夹

c# - 发生未处理的异常后如何重新启动 Windows 服务

php - 正则表达式 - 去除非数字并删除美分(如果有)

regex - 我想解释 Perl 的正则表达式引擎的行为

regex - sed 切换首尾单词顺序

c# - 我可以强制 svcutil.exe 为 WCF 服务生成数据协定吗?

c# - 10,000 后递归加速

java - 如何使用正则表达式在 TreeSet<String> 的范围内查找单词 (java)