繁体   English   中英

C#正则表达式如何提取字符串的第一部分,第二部分和最后一部分

[英]C# Regex how to extract first, second and last part of a string

我的C#正则表达式是

^(?<productno>\d{6})\s(?<type>\w+)\s(?<body>.+?)((?<colorcode>[A-Z]{2}_[A-Z]{1})?|(?<colorcode>[A-Z]{2})?)$

和示例文本是

123456 TYPLV Black Body BK
123456 SAMP Body Black BK_V
123456 TCVERC Black BK_V
INVALID DATA TCVERC Black BK_V

我期待

productno: 123456; type: TYPLV; colorcode: BK
productno: 123456; type: SAMP; colorcode: BK
productno: 123456; type: TCVERC; colorcode: BK
productno: ; type: ; colorcode: 

注意:-第一部分只有在为数字时才有效,如果不是6位数字则不匹配。

基本上,我只需要上面示例中的sno,类型和代码。 如何使用C#正则表达式实现这一目标。 我的正则表达式有什么问题。

我的正则表达式仅适用于

123456 SAMP Black BK_V

而不是

123456 SAMP BK_V

谢谢

试试这个正则表达式:

^(?<productno>\d{6})\s(?<type>\w+)\s(?<body>.*)(?<colorcode>[A-Z]{2}(?:_[A-Z])?)$

为什么不使用简单的String.Split

string[] tokens = "123456 SAMP BK_V".Split(new string[]{" "},StringSplitOptions.RemoveEmptyEntries);
string productno = tokens[0];               // first
string type = tokens.ElementAtOrDefault(1); // second if available, otherwise null
string colorcode = tokens.Last();           // last

读起来不是更好吗? 您可以添加tokens.Length >= 3安全。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM