简体   繁体   English

连字符分隔的浮点数的正则表达式

[英]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 . -1个以上的数字和1或0次出现. and 1+ digits 和1个以上的数字
  • $ - end of string $ -字符串结尾

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 正则表达式返回带括号内浮点数的数字 - Regular expression to return numbers with floating point within parentheses 逗号和空格分隔的数字和连字符分隔的字符串正则表达式 - comma and space separated number and hyphen separated string regular expression 正则表达式可检测由连字符分隔的任意数量的数字 - regular expression detect any number of digits separated by only an hyphen 正则表达式不允许所有相同的数字用连字符分隔 - Regular expression to not allow all same digits separated by hyphen 具有一个连字符(1-5)的数字和具有单个空格的数字(1 2 3 4 5)的正则表达式 - Regular expression for numbers with one hyphen(1-5) and numbers with single spaces (1 2 3 4 5) Javascript正则表达式可查找输入中除浮点数以外的任何字符 - Javascript regular expression to find any character other than floating point numbers in the input 使用正则表达式验证逗号分隔的数字字符串? - Validate comma separated string of numbers with Regular Expression? 仅使用不带正则表达式的 JavaScript 允许数字和连字符 - Allow numbers and Hyphen only using JavaScript without Regular Expression 正则表达式,允许数字,空格,加号,连字符和括号 - Regular expression which allows numbers, spaces, plus sign, hyphen and brackets JavaScript中的正则表达式,用于将负浮点数结果存储在数组中 - regular expression in javascript for negative floating point number result stored in array
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM