我想解析输入字符串并从中提取值。我的输入字符串可能有周、天、小时或分钟。
所以,输入字符串可能是
我希望使用正则表达式提取值。
我如何在.Net中实现这一点?
发布于 2009-07-07 02:52:30
以下正则表达式匹配单数或复数(例如,天或天),只要项目按顺序排列。
//Set the input and pattern
string sInput = "1 Weeks 5 Days 2 Hours 1 Minutes";
string sPattern = "^\s*(?:(?<weeks>\d+)\s*(?:weeks|week))?\s*(?:(?<days>\d+)\s*(?:days|day))?\s*(?:(?<hours>\d+)\s*(?:hours|hour))?\s*(?:(?<minutes>\d+)\s*(?:minutes|minute))?";
//Run the match
Match oMatch = Regex.Match(sInput, sPattern, RegexOptions.IgnoreCase);
//Get the values
int iWeeks = int.Parse(oMatch.Groups["weeks"].Value);
int iDays = int.Parse(oMatch.Groups["days"].Value);
int iHours = int.Parse(oMatch.Groups["hours"].Value);
int iMinutes = int.Parse(oMatch.Groups["minutes"].Value);
发布于 2009-07-07 02:36:09
我认为使用正则表达式对此来说有点过分。如果我是您,我只会标记字符串,将其转换为小写,然后在不同的单词之间切换。这是一个更好的方法来处理你有固定的已知子字符串的情况。
发布于 2009-07-07 02:36:38
Regex中的捕获组包含在括号中(例如,"(\d+ Week)"
)。
命名捕获组使用问号和名称"(?<week>\d+ Week)"
完成。
然后按如下方式返回它们,m.Groups("week").Value
。
完整的正则表达式(未经测试)可能如下所示:
(?<weeks>\d+ weeks?)\s*(?<days>\d+ days?)\s*(?<hours>\d+ hours?)\s*(?<minutes>\d+ minutes?)
https://stackoverflow.com/questions/1091558
复制