tags:

views:

211

answers:

4

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?

+4  A: 

"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!

Bart Kiers
Cheers, man. I need to write my own Blog about this kind of stuff. It's always such an easy answer but you have to search so extensively! May God bless Stackoverflow. Thanks again.
day_trader
@myusername: you're welcome!
Bart Kiers
+5  A: 

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]
spender
A: 

Here is an alternative, not involving regex at all:

try {
    Integer.parseInt( input );
    // Input is numeric
}
catch( Exception ) {
    // Input is not numeric
}
Fragsworth
I tried this one however it's not very elegant is it? I don't want to deliberately throw exceptions... I'm glad we think alike though!
day_trader
You are probably right to avoid it. This is also known as "Expection Handling", which many people would frown on.
Fragsworth
A: 

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));
wds