My idea is something like this but I dont know the correct code
if (mystring.matches(\"[0-9.]+\")){
//do something here
}else{
//do something here
}
<
If you want to check if a number (positive) has one dot and if you want to use regex, you must escape the dot, because the dot means "any char" :-)
see http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html
Predefined character classes
. Any character (may or may not match line terminators)
\d A digit: [0-9]
\D A non-digit: [^0-9]
\s A whitespace character: [ \t\n\x0B\f\r]
\S A non-whitespace character: [^\s]
\w A word character: [a-zA-Z_0-9]
\W A non-word character: [^\w]
so you can use something like
System.out.println(s.matches("[0-9]+\\.[0-9]+"));
ps. this will match number such as 01.1 too. I just want to illustrate the \\.
Simplest
Example:
"123.45".split(".").length();
If you want to -> make sure it's a number AND has only one decimal <- try this RegEx instead:
if(mystring.matches("^[0-9]*\\.?[0-9]*$")) {
// Do something
}
else {
// Do something else
}
This RegEx states:
Note that bullet point #2 is to catch someone entering ".02" for example.
If that is not valid make the RegEx: "^[0-9]+\\.?[0-9]*$"
You could use indexOf()
and lastIndexOf()
:
int first = str.indexOf(".");
if ( (first >= 0) && (first - str.lastIndexOf(".")) == 0) {
// only one decimal point
}
else {
// no decimal point or more than one decimal point
}
I create myself to solve exactly question's problem. I'll share you guys the regex:
^(\d)*(\.)?([0-9]{1})?$
Take a look at this Online Regex to see work properly
Refer documentation if you wish continue to custom the regex
Documentation
I think using regexes complicates the answer. A simpler approach is to use indexOf()
and substring()
:
int index = mystring.indexOf(".");
if(index != -1) {
// Contains a decimal point
if (mystring.substring(index + 1).indexOf(".") == -1) {
// Contains only one decimal points
} else {
// Contains more than one decimal point
}
}
else {
// Contains no decimal points
}