我希望能够使用RegEx来解析范围,例如Windows打印对话框(例如1-50,100-110,111,112)。以下是我目前的代码,我不清楚如何解析其他逗号和数字。我可以解析连字符,但不知道如何使用其他逗号或连字符
private void tboxRowNum_Leave(object sender, EventArgs e)
{
Regex.Replace(tboxRowNum.Text, @"(?<first>\d+)-(?<last>\d+)",
new MatchEvaluator(this.parseSpaceDefinition));
}
private string parseSpaceDefinition(Match m)
{
int first = int.Parse(m.Groups["first"].Value);
int last = int.Parse(m.Groups["last"].Value);
StringBuilder sb = new StringBuilder(first.ToString());
for (int i = first + 1; i <= last; i++)
{
if (spaceItems == 0)
{
if (isNumeric(sb.ToString(), System.Globalization.NumberStyles.Integer))
{
startingSpace = Convert.ToInt32(sb.ToString());
}
}
sb.Append("," + i.ToString().Replace(" ", ""));
spaceItems++;
endingSpace = i;
}
tboxRowDesc.Text = sb.ToString();
return sb.ToString();
}
编辑1:修改后的代码可以获得我想要的内容:
private void tboxRowNum_Leave(object sender, EventArgs e)
{
string[] parts = tboxRowNum.Text.Split(',');
for (int i = 0; i < parts.Length; i++)
{
if (parts[i].IndexOf('-') >= 0)
{
Regex.Replace(parts[i], @"(?<first>\d+)-(?<last>\d+)",
new MatchEvaluator(this.parseSpaceDefinition));
}
else
{
int number;
if(!(int.TryParse(parts[i], out number)))
{
MessageBox.Show("Incomplete/Invalid formula", "Invalid Space Definition");
tboxRowDesc.Text = "";
}
else
{
tboxRowDesc.Text += "," + number;
spaceItems++;
}
}
}
}
答案 0 :(得分:3)
string[] ranges = inputString.split(',');
foreach (string rangeCandidate in ranges) {
// See if matches regex
}
答案 1 :(得分:1)
首先在逗号上拆分它,并为每个部分检查它是否与正则表达式匹配。如果确实如此,那就做你正在做的事情,否则只需使用int.Parse(或int.TryParse来表示健壮性)。