正则表达式在字符串末尾不匹配

时间:2016-06-10 13:31:50

标签: c# regex

我正在尝试从字符串中提取组中的值。我的正则表达式是

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

1 个答案:

答案 0 :(得分:1)

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

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

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

相关问题