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());
Java String - See if a string contains only numbers and characters not words?
What you need is a dictionary of English words. Then you basically scan your input and check if each token exists in your dictionary.
You can find text files of dictionary entries online, such as in Jazzy spellchecker. You might also check Dictionary text file.
Here is a sample code that assumes your dictionary is a simple text file in UTF-8 encoding with exactly one (lower case) word per line:
public static void main(String[] args) throws IOException {
final Set<String> dictionary = loadDictionary();
final String text = loadInput();
final List<String> output = new ArrayList<>();
// by default splits on whitespace
final Scanner scanner = new Scanner(text);
while(scanner.hasNext()) {
final String token = scanner.next().toLowerCase();
if (!dictionary.contains(token)) output.add(token);
}
System.out.println(output);
}
private static String loadInput() {
return "This is a 5gse5qs sample f5qzd fbswx test";
}
private static Set<String> loadDictionary() throws IOException {
final File dicFile = new File("path_to_your_flat_dic_file");
final Set<String> dictionaryWords = new HashSet<>();
String line;
final LineNumberReader reader = new LineNumberReader(new BufferedReader(new InputStreamReader(new FileInputStream(dicFile), "UTF-8")));
try {
while ((line = reader.readLine()) != null) dictionaryWords.add(line);
return dictionaryWords;
}
finally {
reader.close();
}
}
If you need more accurate results, you need to extract stems of your words. See Apache's Lucene and EnglishStemmer
How to check if a string contains both letters and numbers?
Unicode & Character
class
What exactly do you mean by a letter? By a number?
Unicode defines those terms across the various human languages. In Java, the Character
class provides convenient access to those definitions.
We can make short work of this using streams. Calling String::codePoints
generates an IntStream
. We can test each code point for being a letter or digit, until we find one.
String input = "nickname1" ;
boolean hitLetter = input.codePoints().anyMatch( i -> Character.isLetter( i ) ) ;
boolean hitDigit = input.codePoints().anyMatch( i -> Character.isDigit( i ) ) ; ;
boolean containsBoth = ( hitLetter && hitDigit ) ;
See this code run live at IdeOne.com.
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();
}
Related Topics
How to Use Java to Read from a File That Is Actively Being Written To
Selenium Webdriver + Java - Eclipse: Java.Lang.Noclassdeffounderror
Java Thread Priority Has No Effect
How to Correctly Decode Unicode Parameters Passed to a Servlet
Jtable How to Change Background Color
How to Pass Parameters to Anonymous Class
How to Read Request.Getinputstream() Multiple Times
How to Check If a String Contains Only Ascii
Java.Lang.Noclassdeffounderror: Org/Hamcrest/Selfdescribing
Java Date Year Calculation Is Off by Year for Two Days
Differencebetween Double.Parsedouble(String) and Double.Valueof(String)
Is There Any Performance Reason to Declare Method Parameters Final in Java
"Non-Static Variable This Cannot Be Referenced from a Static Context" When Creating an Object
What Are the Differences Between "Generic" Types in C++ and Java
Java, How to Implement a Shift Cipher (Caesar Cipher)