Check string for alphabetic characters

If I have the strings "hello8459" and "1234", how would I know which one was alphabetic? I have tried:

//Checking for numerics in an if...
Pattern.matches("0-9", string1);

      

However, this doesn't work at all. Can anyone advise?

+2


source to share


6 answers


"0-9" matches exactly this, line: "0-9". What you probably wanted to do is "[0-9] +", which matches one or more digits.

And you can use the String matches (...) method:



boolean onlyDigits = "1234578".matches("\\d+");

      

Be careful when parsing a primitive int or a long int after checking "onlyDigits": it can be a large number, for example 123145465124657897456421345487454, which does not fit into the primitive data type, but passes the coincidence check (...)!

+5


source


On the one hand, you are asking how to recognize characters in the alphabet, but your code seems to be trying to detect a number.

For numbers:

[0-9]

      



For the alphabet:

[a-zA-Z]

      

+6


source


Ruby has a method on the String class called "string" .is_alphabet? which says if the string only contains an alphabet character or not. But unfortunately there is no way in java to check if a string only contains an alphabetic character, but don't worry, you can do something like

   boolean isAlphabet = "1234".matches("[a-zA-Z]+") which'll returns false
   boolean isAlphabet = "hello".matches("[a-zA-Z]+") which'll return true cause it contains only alphabet.

      

+2


source


Here's a non-regular expression alternative:

try {
    Integer.parseInt( input );
    // Input is numeric
}
catch( Exception ) {
    // Input is not numeric
}

      

+1


source


You don't want to check if there are any numbers, you want to check if there is something that is not a number (or at least that's what your question is talking about, maybe not what you mean). Thus, you want to deny your character class and look for the presence of anything that is not a digit, instead of trying to find anything that is a digit. An empty string, of course. In code:

boolean isNumeric = !(str.matches("[^0-9]") || "".equals(str));

      

+1


source


The way to test all characters in a string is to turn it into a char array:

char[] check = yourstring.toCharArray();

      

And then create a for loop that tests all characters separately:

for(int i=0; i < check.length; i++){
    if(!Character.isDigit(check[i])){
        System.out.println("Not numberal");
        }
    }

      

+1


source







All Articles