Java String - See if a string contains only numbers and not letters
If you'll be processing the number as text, then change:
if (text.contains("[a-zA-Z]+") == false && text.length() > 2){
to:
if (text.matches("[0-9]+") && text.length() > 2) {
Instead of checking that the string doesn't contain alphabetic characters, check to be sure it contains only numerics.
If you actually want to use the numeric value, use Integer.parseInt()
or Double.parseDouble()
as others have explained below.
As a side note, it's generally considered bad practice to compare boolean values to true
or false
. Just use if (condition)
or if (!condition)
.
How to check if a string contains only digits in Java
Try
String regex = "[0-9]+";
or
String regex = "\\d+";
As per Java regular expressions, the +
means "one or more times" and \d
means "a digit".
Note: the "double backslash" is an escape sequence to get a single backslash - therefore, \\d
in a java String gives you the actual result: \d
References:
Java Regular Expressions
Java Character Escape Sequences
Edit: due to some confusion in other answers, I am writing a test case and will explain some more things in detail.
Firstly, if you are in doubt about the correctness of this solution (or others), please run this test case:
String regex = "\\d+";
// positive test cases, should all be "true"
System.out.println("1".matches(regex));
System.out.println("12345".matches(regex));
System.out.println("123456789".matches(regex));
// negative test cases, should all be "false"
System.out.println("".matches(regex));
System.out.println("foo".matches(regex));
System.out.println("aa123bb".matches(regex));
Question 1:
Isn't it necessary to add
^
and$
to the regex, so it won't match "aa123bb" ?
No. In java, the matches
method (which was specified in the question) matches a complete string, not fragments. In other words, it is not necessary to use ^\\d+$
(even though it is also correct). Please see the last negative test case.
Please note that if you use an online "regex checker" then this may behave differently. To match fragments of a string in Java, you can use the find
method instead, described in detail here:
Difference between matches() and find() in Java Regex
Question 2:
Won't this regex also match the empty string,
""
?*
No. A regex \\d*
would match the empty string, but \\d+
does not. The star *
means zero or more, whereas the plus +
means one or more. Please see the first negative test case.
Question 3
Isn't it faster to compile a regex Pattern?
Yes. It is indeed faster to compile a regex Pattern once, rather than on every invocation of matches
, and so if performance implications are important then a Pattern
can be compiled and used like this:
Pattern pattern = Pattern.compile(regex);
System.out.println(pattern.matcher("1").matches());
System.out.println(pattern.matcher("12345").matches());
System.out.println(pattern.matcher("123456789").matches());
Check if a string contains only digits and white space in java Android
As @ADM suggested in comment you can update your regex [0-9]+
with below
[0-9 ]+
so it look like
String Cardresult = edtCashCard.getText().toString();
if (Cardresult.matches("[0-9 ]+")){
Toast.makeText(getApplicationContext(), "Good Job the strings are numbers", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getApplicationContext(), "Error the string contains character", Toast.LENGTH_SHORT).show();
}
Check if string contains a particular digit only (e.g. 111)
You can use this regex, which uses group to capture the first digit and then uses back-reference to ensure that the following digits all are same,
^(\d)?\1*$
Explanation:
^
- Start of string(\d)?
- Matches one digit and captures in group1 and?
makes it optional to allow matching empty strings.\1*
- Matches the same digit zero or more times$
- End of string
Regex Demo
Java code,
List<String> list = Arrays.asList("5","5555","11111","22222","1234", "");
list.forEach(x -> {
System.out.println(x + " --> " + x.matches("(\\d)?\\1*"));
});
Prints,
5 --> true
5555 --> true
11111 --> true
22222 --> true
1234 --> false
--> true
Check and extract a number from a String in Java
The solution I went with looks like this:
Pattern numberPat = Pattern.compile("\\d+");
Matcher matcher1 = numberPat.matcher(line);
Pattern stringPat = Pattern.compile("What is the square of", Pattern.CASE_INSENSITIVE);
Matcher matcher2 = stringPat.matcher(line);
if (matcher1.find() && matcher2.find())
{
int number = Integer.parseInt(matcher1.group());
pw.println(number + " squared = " + (number * number));
}
I'm sure it's not a perfect solution, but it suited my needs. Thank you all for the help. :)
How would I be able to determine if a string contains only one digit?
Try this. Single digit in password vs no digit or more than one in password.
for (String pw : new String[]{"with1digit", "withtwo22digits","withNodigits",
"with2scatt2reddi3gits"}) {
boolean m = pw.matches("[^\\d]*\\d[^\\d]*");
System.out.println(m + " : " + pw);
}
Prints the following:
true : with1digit
false : withtwo22digits
false : withNodigits
false : with2scatt2reddi3gits
Example usage.
if (onlyOneDigit(password)) {
// it's good
} else {
// warn user
}
public static boolean onlyOneDigit(String pw) {
return pw.matches("[^\\d]*\\d[^\\d]*");
}
And her is another way
public static boolean onlyOneDigit(String pw) {
// get rid of the first digit
String save =pw.replaceFirst("\\d","");
// replace the next digit with a #
save = save.replaceFirst("\\d", "#");
// if save contains # it had more than 1 digit
// or if save equals the original password
// then there were no digits.
return !(save.equals(pw) || save.contains("#"));
}
Related Topics
How to Make a Deep Copy of Java Arraylist
Compare One String with Multiple Values in One Expression
Midpoint Between Two Latitude and Longitude
Adding Chartpanel to Jtabbedpane Using JPAnel
JPA Query Selecting Only Specific Columns Without Using Criteria Query
Hibernate Saveorupdate Behavior
Bitset to and from Integer/Long
Jfreechart Candlestick Chart Weird Behaviour on Drag
Java Executors: How to Set Task Priority
What Is the Purpose of Defining a Package in a Java File
What Are Good Installanywhere Replacements for Installing a Java Ee Application
Getting an Attribute Value in Xml Element
How to Create Splash Screen with Transparent Background in Javafx
Exception in Thread "Main" Java.Util.Nosuchelementexception