-1

Possible Duplicate:
Simple way to determine if string is only characters, or to check if string contains any numbers in Java

I want to find if a given String has any alphabetic or numeric characters. How would I do this using java?

Thanks

Community
  • 1
  • 1
Sameek Mishra
  • 9,174
  • 31
  • 92
  • 118
  • 2
    "find" in what? Please provide a more thorough explanation of what you want to achieve and/or an example (if possible). – Joachim Sauer Jul 06 '11 at 12:09
  • 4
    Did you try searching? http://stackoverflow.com/questions/5238491/simple-way-to-determine-if-string-is-only-characters-or-to-check-if-string-conta – Emyr Jul 06 '11 at 12:09
  • Your question doesn't make much sense as written, but nevertheless... StackOverflow can be cruel to people whose native language is not English (5 downvotes?!?). Did you mean to ask, "How can I determine whether a String represents a number"? If so, then you can you can use either regular expressions or the Apache StringUtils library as has been suggested. You may also see some code examples where people use "Double.parseDouble()" and try to catch a NumberFormatException... but it's really not good practice to use try-catch blocks to drive logic in that manner. – Steve Perkins Jul 06 '11 at 12:25

3 Answers3

3
String s = "%$a*";
Pattern p = Pattern.compile("[a-zA-Z0-9]");
Matcher m = p.matcher(s);
if (m.find())
  System.out.println("The string \"" + s + "\" contains alphanumerical characters.");
SteeveDroz
  • 6,006
  • 6
  • 33
  • 65
  • 2
    This only handles ASCII alphabetical characters. – ewan.chalmers Jul 06 '11 at 12:19
  • +1 for @sudocode: *especially* if the OP is not a native english speaker, chances are he needs to support non-ASCII characters. – Joachim Sauer Jul 06 '11 at 12:30
  • 1
    @sudocode and @Joachim Sauer I agree, but for my defense, I had not much to work with. My answer is correct as long as the question remains that vague. – SteeveDroz Jul 06 '11 at 12:32
  • @Oltarus: I agree with the "not much to work with" part. *But* `ä`, `ö` and `ß` are certainly alphabetic, just as `ě`, `ë` and `Ç`. – Joachim Sauer Jul 06 '11 at 12:34
1

Take a look at this: http://www.regular-expressions.info/java.html

Ovais Khatri
  • 3,201
  • 16
  • 14
1

There are two convenience methods in the Character class that would help you

All that's required is transforming a String to a character array, and then stepping through the array.

mre
  • 43,520
  • 33
  • 120
  • 170