Java library to check whether a String contains a number *without* exceptions

前端 未结 5 487
长情又很酷
长情又很酷 2020-12-18 00:50

I\'m looking for a method that returns a boolean if the String it is passed is a valid number (e.g. \"123.55e-9\", \"-333,556\"). I don\'t want to just do:

5条回答
  •  一生所求
    2020-12-18 01:09

    Yeah a regular expression should do the trick. I only know .Net regexp but all regex languages are fairly similar so this should get you started. I didn't test it so you might want to kick it around a bit with the Java regex class.

    "-?(([0-9]{1,3}(,[0-9{3,3})*)|[0-9]*)(\.[0-9]+(e-?[0-9]*)?)?"
    

    Some of the Regex control syntax:
    ? - Optional element
    | - OR operator. Basically I allowed numbers with or without commas if they were formatted correctly.
    [ ] - Set of allowed characters
    { , } - Minimum maximum of element
    * - Any number of elements, 0 to infinity
    + - At least one element, 1 to infinity
    \ - Escape character
    . - Any character (Hence why it was escaped)

提交回复
热议问题