Created
June 13, 2020 16:06
-
-
Save ajaypro/e3e434177c13d3ca20a9fac4ef03978b to your computer and use it in GitHub Desktop.
Using Regex check whether string is numeric
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fun main() { | |
val str = "12345" | |
var numeric = false | |
numeric = str.matches("-?\\d+(\\.\\d+)?".toRegex()) | |
if (numeric) | |
println("$str is a number") | |
else | |
println("$str is not a number") | |
} | |
In the matches() method, | |
-? allows zero or more - for negative numbers in the string. | |
\\d+ checks the string must have at least 1 or more numbers (\\d). | |
(\\.\\d+)? allows zero or more of the given pattern (\\.\\d+) in which | |
\\. checks if the string contains . (decimal points) or not | |
If yes, it should be followed by at least one or more number \\d+. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment