正则表达式,用于一行中4个整数或2个双精度的精确匹配(Regular Expression for exact match of either 4 integers or 2 doubles in a

编程入门 行业动态 更新时间:2024-10-27 19:18:20
正则表达式,用于一行中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.

更多推荐

本文发布于:2023-04-28 14:30:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1332450.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:整数   精度   精确   正则表达式   Regular

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!