简体   繁体   中英

Check String for Alphabetical Characters

If I have the strings "hello8459" and "1234", how would I go about detecting which one had the alphabetical characters in? I've been trying:

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

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

On one hand you are asking how to detect alphabet chars, but your code seems to be attempting to detect numerics.

For numerics:

[0-9]

For alphabet:

[a-zA-Z]

"0-9" matches just that, the string: "0-9". What you probably meant to do is "[0-9]+" which matches one ore more digits.

And you can use String's matches(...) method:

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

Be careful though, when parsing to a primitive int or long after checking 'onlyDigits': it might be a large number like 123145465124657897456421345487454 which does not fit in a primitive data type but passes the matches(...) test!

In Ruby there is method in String class called "string".is_alphabet? which tells that if string contains only alphabet character or not. But Unfortunately in java there is no method to check if a string contains only alphabetic character in it,But No worries 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.

Here is an alternative, not involving regex at all:

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

You don't want to check whether there are any numbers, you want to check whether there is anything that is not a number (or at least that is what your question says, maybe not what you meant). So you want to negate your character class and search for the presence of anything that is not a digit, instead of trying to find anything that is a digit. There's also the empty string of course. In code:

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

A way to check all of the characters in a string is to turn it into a char array:

char[] check = yourstring.toCharArray();

And then make a for loop that checks all of the characters individually:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM