c# - 在 C# 中使用正则表达式分组的子字符串

标签 c# .net regex string extract

我想使用正则表达式从字符串中检索子字符串。

仅供引用:这些字符串值是邮件中的主题

String1 = "Acceptance :DT_Ext_0062-12_012ed2 [Describe]"

string2 = "Acceptance : DT_Ext_0062-12_012 (ed.2) , Describe"

string3 = "Acceptance of : DT_Ext_0062-12_012 (ed.2) , Describe to me"

子字符串:

sub1 = Acceptance            <Mail Type : like Reject or Accept>
sub2 = DT_Ext_0062-12_012    <ID : unique identifier>
sub3 = ed2                   <Edition of mail, like : ed1, ed2, ed3 ...so on>
sub4 = Describe              <Description of the mail>

我如何为上述两个字符串编写正则表达式(单独编写或为两者编写一个正则表达式)以获得相同的输出。

我认为可以使用匹配组来检索数据。但我对正则表达式很陌生。

最佳答案

试试这个:

// string strTargetString = @"Acceptance :DT_Ext_0062-12_012ed2 [Describe]";
// string strTargetString = @"Acceptance : DT_Ext_0062-12_012 (ed.2) , Describe";
string strTargetString = @"Acceptance of : DT_Ext_0062-12_012 (ed.2) , Describe to me";

 const string strRegex = @"\.*:\s*(DT_Ext_\d{4}-\d{2}_\d{3})\s*\W*(ed)\.?(\d+)(\W*[,])?(.*)";


RegexOptions myRegexOptions = RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.CultureInvariant;
Regex myRegex = new Regex(strRegex, myRegexOptions);


foreach(Match myMatch in myRegex.Matches(strTargetString))
{
    if(myMatch.Success)
    {
        // Add your code here
        var value = new {
            Value1 = myMatch.Groups[1].Value,
            Value2 = myMatch.Groups[2].Value,
            Value3 = myMatch.Groups[3].Value,
            Value4 = myMatch.Groups[5].Value,
        };
    }
}

关于c# - 在 C# 中使用正则表达式分组的子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18270363/

相关文章:

java - 正则表达式字符集 [^\\w\\d\\s\\&] 不起作用

c# - 序列化/反序列化两个列表后,List.Remove 不会删除任何项目

c# - 服务引用问题

.net - AutoResetEvents/ManualResetEvents 在内部使用 Win32 信号量或互斥体吗?

java - 如何在.NET 中使用 DES 算法?

c# - .NET/C# - 将 char[] 转换为字符串

javascript - 正则表达式更改 html 元素类与 javascript 不工作

正则表达式匹配偶数、非零数字

c# - 无法将派生类转换为其基类型

c# - 如何在 C# 上将 MySQL 查询转换为 JSON