4

how would i check a string for special characters such as $%#, and numbers? I only want chars, ex abcd.

the only method i can think of is to make an arraylist of the alphabet and check each index to see if it is in the arraylist.

thanks

scurker
  • 4,733
  • 1
  • 26
  • 25
Andres Lamberto
  • 106
  • 2
  • 3
  • 9

2 Answers2

10

RegEx is probably your best bet:

 Pattern p = Pattern.compile("[a-zA-Z]");
 Matcher m = p.matcher(sourceString);
 boolean b = m.matches();
lukiffer
  • 11,025
  • 8
  • 46
  • 70
  • 3
    You could also shorten it by calling sourceSting.matches("[a-zA-Z]") – Zach May 02 '11 at 01:43
  • @Zach - ... at the cost of recompiling the pattern each time you do it. (Admittedly, @lukiffer's code doesn't hoist the pattern creation.) – Stephen C May 02 '11 at 04:32
1

you can try a regex:

Pattern p = Pattern.compile("[^a-zA-Z]");
if(p.matcher(string).find()){
//something is not a letter
}
ratchet freak
  • 47,288
  • 5
  • 68
  • 106