### 正则表达式分组划分问题

``````+33.22+10.22+11.22+4.43+4.43
``````

``````33.22+10.22+11.22+4.43+4.43
``````

``````^(([+-]?\d{1,2}\.\d{1,2})|([+-]?\d{1,3}))(([+-]\d{1,2}\.\d{1,2})|([+-]\d{1,3})){0,4}\$
``````

``````^(([+-]?\d{1,2}\.\d{1,2})|([+-]?\d{1,3}))(([+-]\d{1,2}\.\d{1,2})|([+-]\d{1,3}))(([+-]\d{1,2}\.\d{1,2})|([+-]\d{1,3}))(([+-]\d{1,2}\.\d{1,2})|([+-]\d{1,3}))(([+-]\d{1,2}\.\d{1,2})|([+-]\d{1,3}))\$
``````

#### 1 个答案:

``````if (/^(?:[+-]?(?:\d{1,2}\.\d{1,2}|\d{1,3})\b){1,5}\$/.test(s)) {
return s.match(/[+-]?\d+(?:\.\d+)?/g);
}
``````

• `^`-字符串的开头
• `(?:[+-]?(?:\d{1,2}\.\d{1,2}|\d{1,3})\b){1,5}`-重复1到5次
• `[+-]?`-可选的`+``-`
• `(?:\d{1,2}\.\d{1,2}|\d{1,3})`-与任何一个非捕获组匹配
• `\d{1,2}\.\d{1,2}`-1或2位数字，`.`和1或2位数字
• `|`-或
• `\d{1,3}`-1、2或3位数字
• `\b`-单词边界
• `\$`-字符串的结尾。

`.match(/[+-]?\d+(?:\.\d+)?/g`提取`-` / `+`之后的所有子字符串-1个以上的数字-可选的`.`和1个以上的数字模式，来自经过验证的字符串。

``````var s = "+33.22+10.22+11.22+4.43+4.43";
if (/^(?:[+-]?(?:\d{1,2}\.\d{1,2}|\d{1,3})\b){1,5}\$/.test(s)) {
console.log(s.match(/[+-]?\d+(?:\.\d+)?/g));
}``````

``````var s = "+33.22+10.22+11.22+4.43+4.43";
var m = Regex.Match(s, @"^([+-]?(?:\d{1,2}\.\d{1,2}|\d{1,3})\b){1,5}\$");
if (m.Success)
{
var captures = m.Groups[1].Captures.Cast<Capture>().Select(p => p.Value).ToList();
foreach (var x in captures)
Console.WriteLine(x);
}
else
{
Console.WriteLine("No match!");
}
``````

``````+33.22
+10.22
+11.22
+4.43
+4.43
``````