简体   繁体   中英

Regular expression for hyphen separated floating point numbers

Need some help in designing regular expression to validate hyphen separated floating point numbers in Javascript. So far I have managed to achieve this 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. 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. Thus, 2 dots are allowed.

You may fix the pattern like this:

^\d+(?:\.\d+)?(?:-\d+(?:\.\d+)?)*$

See the regex demo

Details

  • ^ - start of string
  • \\d+ - 1+ digits
  • (?:\\.\\d+)? - an optional non-capturing group:
    • \\. - a dot
    • \\d+ - 1+ digits
  • (?:-\\d+(?:\\.\\d+)?)* - an non-capturing group matching 0+ occurrences of
    • - - a hyphen
    • \\d+(?:\\.\\d+)? - 1+ digits and 1 or 0 occurrences of . and 1+ digits
  • $ - end of string

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM