Skip to content

Instantly share code, notes, and snippets.

@ajaypro
Created June 13, 2020 16:06
Show Gist options
  • Save ajaypro/e3e434177c13d3ca20a9fac4ef03978b to your computer and use it in GitHub Desktop.
Save ajaypro/e3e434177c13d3ca20a9fac4ef03978b to your computer and use it in GitHub Desktop.
Using Regex check whether string is numeric
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