Skip to main content
 首页 » 编程设计

c#之伪 IPv4 正则表达式

2024年02月02日24youxin

假设最大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>创建命名组的语法仅在紧跟在左括号之后有效,否则 ?意思是“使前一个元素可选”。由于 ? 之前没有前一个元素, 你收到一个错误。