您可以使用组来提取较大的图案的特定部分。你的情况:
offerDate\((\d+),(\d+)\)
然后您可以封装成函数:
static IEnumerable<Range> ParseOfferDateRanges(string input)
{
var matches = Regex.Matches(input, @"offerDate\((\d+),(\d+)?\)");
return matches
.Cast<Match>()
.Select(ParseOfferDateMatch)
.ToList();
}
static Range ParseOfferDateMatch(Match match)
{
var fromValue = match.Groups[1].Value;
var toGroup = match.Groups[2];
var to = toGroup.Success
? short.Parse(toGroup.Value)
: (short?)null;
return new Range()
{
From = short.Parse(fromValue),
To = short.Parse(toValue)
};
}
我假设你有一个Range
结构,看起来像以下,但在C#7,你还可以返回一个元组:
public struct Range
{
public short From;
public short? To;
}
请说明您当前的代码有什么问题 –
我只是想检查我的字符串是否以“offerDate”开头。如果它是真的,那么只有我需要存储这个数字。当前的代码提取数字并存储在列表中,但是它不检查字符串是否以“OfferDate”开头 –
要澄清,“StringToBePassed”可以包含'offerDate(1,30)'的_多个实例吗?我更新的答案假定您使用'Match'的倍数,但如果这个假设是错误的,我可以恢复到我的原始版本,它只解析一个实例。 –