Regex testXpress = new Regex(
@"^\s*(?:" +
@"(?:" +
@"(?:(?<low_bound>\d+(?:\.\d+)?))" +
@"\s*(?:-|~)\s*" +
@"(?:(?<high_bound>\d+(?:\.\d+)?))" +
")" +//0.78 - 1.23; 1-2.24; 4.3 -6; 5-9
@"|(?:(?:≤|(?:<=))\s*(?<high_bound>\d+(?:\.\d+)?))" + //<= 1.23; ≤1.12; <=1; ≤ 2
@"|(?:(?:≥|(?:>=))\s*(?<low_bound>\d+(?:\.\d+)?))" + //>= 1.23; ≥1.12; >=1; ≥ 2
@"|(?:(?:<|<)\s*(?<high_bound>\d+(?:\.\d+)?))" + //< 1.23; <1.12; <1; < 2
@"|(?:(?:>|>)\s*(?<low_bound>\d+(?:\.\d+)?))" + //> 1.23; >1.12; >1; > 2
@"|(?<accurate>\d+(?:\.\d+)?)" + // 12.45; 36
@")\s*$"
);
Match mc = testXpress.Match(textBox1.Text);
if (mc.Success)
{
foreach (Group gp in mc.Groups)
{
//string name = ?这里怎么获得捕获组的名字》?
foreach (Capture cp in gp.Captures)
{
//do something with name and cp.value
}
}
}
正则表达式匹配成功后,要遍历gropus中的group,并根据组名对捕获结果进行处理。
上面给出的正则表达式只是其中最简单的一个。