2016-06-10 115 views
0

我想从字符串中提取组中的值。我的正则表达式是正则表达式在字符串末尾不匹配

string str = @"DEMOV 1'07"" MOT Lifestyle 503080 Pure Rain Nozzle Feb 13 472000"; 

const string type = @"(?<type>\w+)"; 
const string minutes = @"((?<minutes>\d+)\')?"; 
const string seconds = @"((?<seconds>\d+)\"")?"; 
const string body = @"(?<body>.+)"; 
const string id = @"(?<id>\s\d{6})?"; 

var pattern1 = String.Format(@"^{0}(?:\s\w+)?\s({1}{2}|{1}|{2})\s?{3}{4}$", type, minutes, seconds, body, id); 
var m1 = Regex.Match(str, pattern1); 

我得到的比赛,但该组没有得到最后5位数字。

有谁能告诉我我在做什么错在这里?

请在下面找到我得到的输出。

enter image description here

+0

因为' 。+'是贪婪的,它已经匹配这些数字,因此可选组不匹配。你可以使用'。+?'进行延迟匹配。 –

+0

是的。有效。谢谢 –

回答

1

使用非贪婪版本(使用.+?body),不空格添加到id组:

const string body = @"(?<body>.+?)"; 
const string id = @"\s(?<id>\d{6})?"; 

在行动:https://dotnetfiddle.net/L1yL3C

+0

是的,它的工作。谢谢。我如何得到组的价值即。我如何获得id的组值? –

+0

我想通了。 var min = m1.Groups [“minutes”]。Value; –

+0

'm1.Groups [“id”]' – Jcl