gpt4 book ai didi

c# - 如何显示哪个子正则表达式匹配失败?

转载 作者:太空宇宙 更新时间:2023-11-03 11:53:30 25 4
gpt4 key购买 nike

我正在使用正则表达式来验证用户输入。以下代码收集可使用 theMatch.Groups["identifier"] 访问的匹配项。如何获取每个组中不匹配的子字符串列表?

#region Using directives

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


namespace RegExGroup
{

class Test
{
public static void Main( )
{
string string1 = "04:03:27 127.0.0.0 comcom.com";

// group time = one or more digits or colons followed by space
Regex theReg = new Regex( @"(?<time>(\d|\:)+)\s" +
// ip address = one or more digits or dots followed by space
@"(?<ip>(\d|\.)+)\s" +
// site = one or more characters
@"(?<site>\S+)" );

// get the collection of matches
MatchCollection theMatches = theReg.Matches( string1 );

// iterate through the collection
foreach ( Match theMatch in theMatches )
{
if ( theMatch.Length != 0 )
{
Console.WriteLine( "\ntheMatch: {0}",
theMatch.ToString( ) );
Console.WriteLine( "time: {0}",
theMatch.Groups["time"] );
Console.WriteLine( "ip: {0}",
theMatch.Groups["ip"] );
Console.WriteLine( "site: {0}",
theMatch.Groups["site"] );
}
}
}
}
}

所以如果用户输入 0xx:03:27 127.0.0.0 ?.com
我要输出

 time:  0xx:03:27
site: ?.com

此外,有人有关于在 C# 中使用正则表达式的良好引用资料吗?
谢谢,感谢任何帮助。

最佳答案

您是在问如何确定哪个特定捕获组匹配失败?据我所知,一旦匹配失败,您将无法提取此类信息。如果失败就是失败;无法检索到部分匹配尝试信息。您可以做的是按原样应用整个正则表达式以按所需顺序检查模式。然后,如果失败,请分别尝试正则表达式的每个部分并告诉用户哪一个失败(时间、IP、站点)。这种方法在这种情况下可能有意义,但可能不适用于所有类型的模式。

关于引用,这里有几个链接:

如果您正在寻找一本好书,那么最受欢迎的是 Jeffrey Friedl 的 Mastering Regular Expressions .最近有正面评价的书是 Regular Expressions Cookbook .

关于c# - 如何显示哪个子正则表达式匹配失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1392009/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com