Check if a given string is a valid number (Integer or Floating Point) in Java | SET 2 (Regular Expression approach)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
Input : str = "11.5" Output : true Input : str = "abc" Output : false Input : str = "2e10" Output : true Input : 10e5.4 Output : false
Check if a given string is a valid Integer
For integer number : Below is the regular definition for an integer number.
sign -> + | - | epsilon digit -> 0 | 1 | .... | 9 num -> sign digit digit*
Hence one of the regular expression for an integer number is
abc is not a valid integer number 1234 is a valid integer number
Below are other short-hands regular expression for an integer number
[+-]?[0-9]+ [+-]?\d\d* [+-]?\d+
Check if a given string is a valid floating point number
For floating point number : Below is the regular definition for a floating point number.
sign -> + | - | epsilon digit -> 0 | 1 | .... | 9 digits -> digit digit* optional_fraction -> . digits | epsilon optional_exponent -> ((E | e) (+ | - | epsilon) digits) | epsilon num -> sign digits optional_fraction optional_exponent
Hence one of the regular expression for a floating number is
10e5.4 is not a valid float number 2e10 is a valid float number
Below is other short-hand regular expression for a float number
This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.