C#开发中如何用正则匹配指定规则字符串并拆分出四个指定片段
C# 正则匹配实现方案
最终正则表达式
^(?<part1>.*?)_(?<part2>\d+[DM])(?<part3>.{4}-.{4})(?<part4>.{3})$
分组说明
四个命名分组正好对应你需要拆分的四个片段:
part1:匹配最后一个下划线之前的所有前缀内容,对应示例中的MRT01part2:匹配最后一个下划线后「整数+D/M」格式的片段,对应示例中的60Dpart3:匹配后缀前8位,自动校验第5位为短横线,对应示例中的OOO3-0013part4:匹配后缀最后3位,对应示例中的577
规则校验覆盖
- 自动满足前缀规则:最后一个下划线后必须为数字+D/M格式,支持前缀包含多个下划线
- 自动满足后缀规则:
part3+part4总长度为12位,且part3固定第5位为短横线
C# 调用示例
using System; using System.Text.RegularExpressions; class RegexTest { static void Main() { string inputStr = "MRT01_60DOOO3-0013577"; Regex reg = new Regex(@"^(?<part1>.*?)_(?<part2>\d+[DM])(?<part3>.{4}-.{4})(?<part4>.{3})$"); Match matchResult = reg.Match(inputStr); if (matchResult.Success) { string res1 = matchResult.Groups["part1"].Value; string res2 = matchResult.Groups["part2"].Value; string res3 = matchResult.Groups["part3"].Value; string res4 = matchResult.Groups["part4"].Value; // 测试输出 Console.WriteLine($"{res1}\n{res2}\n{res3}\n{res4}"); } } }
可选配置
如果需要支持小写的d/m匹配,创建Regex对象时添加RegexOptions.IgnoreCase参数即可。
内容的提问来源于stack exchange,提问作者eric.bryan
相关产品推荐
相关产品推荐

