[英]Regular expression for hyphen separated floating point numbers
Need some help in designing regular expression to validate hyphen separated floating point numbers in Javascript. 在设计正则表达式以验证Java中连字符分隔的浮点数时需要一些帮助。 So far I have managed to achieve this RegEx:
到目前为止,我已经成功实现了此RegEx:
(^((\\d)+(\.[0-9]+)?)(\-)?((\\d)+(\.[0-9]+)?)$)|^(\\d+)$
It matches the following: 它符合以下条件:
1) 2
2) 2.10
3) 3.10-3.14
The problem with this one is that its also matching "3.103.310" which is wrong number. 这个问题是,它也匹配错误的数字“ 3.103.310”。 Much appreciate any help in fixing this issue.
非常感谢您为解决此问题提供的任何帮助。
The problem comes from the first alternative that matches 1 or more digits with an optional fractional part ( (\\d)+(\\.[0-9]+)?
) and then matches a hyphen and again 1+ digits and again an optional fractional part. 问题来自第一个备选方案,该备选方案将一个或多个数字与可选的小数部分(
(\\d)+(\\.[0-9]+)?
)匹配,然后再匹配一个连字符,再匹配一个1+个数字,再匹配一个可选字符小数部分。 Thus, 2 dots are allowed. 因此,允许2个点。
You may fix the pattern like this: 您可以像这样修复模式:
^\d+(?:\.\d+)?(?:-\d+(?:\.\d+)?)*$
See the regex demo 见正则表达式演示
Details 细节
^
- start of string ^
-字符串的开头 \\d+
- 1+ digits \\d+
-1个以上数字 (?:\\.\\d+)?
- an optional non-capturing group: \\.
- a dot \\d+
- 1+ digits \\d+
-1个以上数字 (?:-\\d+(?:\\.\\d+)?)*
- an non-capturing group matching 0+ occurrences of (?:-\\d+(?:\\.\\d+)?)*
-匹配0+次出现的非捕获组
-
- a hyphen -
连字符 \\d+(?:\\.\\d+)?
- 1+ digits and 1 or 0 occurrences of .
.
and 1+ digits $
- end of string $
-字符串结尾
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.