正则表达式,用于一行中4个整数或2个双精度的精确匹配(Regular Expression for exact match of either 4 integers or 2 doubles in a line)
我试图识别文件中具有4个整数或2个双精度值的行。 我的正则表达式如下:
var match = new Regex(@"^(?<Values>(((\d+\s*){4})|(\d+\.\d+\s*){2}))$");要解析的文件中的行样本:
element 1 2 8 24 2 1 1 0 1 129 2 2 0 0 30.200001 1000.0000 208 0 0 0 0 0 0 0 ..... .....在这里,我的正则表达式正确匹配上面的第4和第5行。没关系。 但是,它也匹配第3行(0 1 129)。 这对我来说是个问题。 请建议:
为什么我的正则表达式匹配第3行。 正确的正则表达式恰好匹配4 no。 整数或2没有。 一行中的双值。I am trying to identify lines in a file that have either 4 integer or 2 double values. My regular expression is as below:
var match = new Regex(@"^(?<Values>(((\d+\s*){4})|(\d+\.\d+\s*){2}))$");Sample of lines in the file getting parsed:
element 1 2 8 24 2 1 1 0 1 129 2 2 0 0 30.200001 1000.0000 208 0 0 0 0 0 0 0 ..... .....Here, my regular expression matches correctly for above lines no 4 & 5. That's ok. But, it's also matching line no 3 (0 1 129). That's the problem for me. Kindly suggest:
Why my regular expression is matching line no 3. Correct regular expression that matches exactly either 4 no. of integers or 2 no. of double values in a line.最满意答案
我想这就是你要找的东西:
^(((\d+\s+){3}\d+)|(\d+\.\d*\s+\d+\.\d*))\s*$在这里测试过 。
说明
^( ((\d+\s+){3}\d+) # 4 numbers separated by at least one space | (\d+\.\d*\s+\d+\.\d*) # 2 floats separated by at least one space )\s*$ # optional spaces at end of line (e.g., line 4)您最初尝试的错误是数字之间缺少必要的空格。
I think this is what you're looking for:
^(((\d+\s+){3}\d+)|(\d+\.\d*\s+\d+\.\d*))\s*$Tested here.
Explanations
^( ((\d+\s+){3}\d+) # 4 numbers separated by at least one space | (\d+\.\d*\s+\d+\.\d*) # 2 floats separated by at least one space )\s*$ # optional spaces at end of line (e.g., line 4)The error in your initial attempt was the lack of mandatory space between numbers.
更多推荐
发布评论