views:

3809

answers:

7

How do you check a string if there is a special character like: [,],{,},{,),*,|,:,>,etc.?

+1  A: 

What do you exactly call "special character" ? If you mean something like "anything that is not alphanumeric" you can use org.apache.commons.lang.StringUtils class (methods IsAlpha/IsNumeric/IsWhitespace/IsAsciiPrintable).

If it is not so trivial, you can use a regex that defines the exact character list you accept and match the string against it.

zim2001
+1  A: 

All depends on exactly what you mean by "special". In a regex you can specify

  • \W to mean non-alpahnumeric
  • \p{Punct} to mean punctuation characters

I suspect that the latter is what you mean. But if not use a [] list to specify exactly what you want.

djna
+1  A: 

Have a look at the java.lang.Character class. It has some test methods and you may find one that fits your needs.

Examples: Character.isSpaceChar(c) or !Character.isJavaLetter(c)

Andreas_D
A: 

Visit each character in the string to see if that character is in a blacklist of special characters; this is O(n*m).

The pseudo-code is:

for each char in string:
  if char in blacklist:
    ...

The complexity can be slightly improved by sorting the blacklist so that you can early-exit each check. However, the string find function is probably native code, so this optimisation - which would be in Java byte-code - could well be slower.

Will
+1  A: 

First you have to exhaustively identify the special characters that you want to check.

Then you can write a regular expression and use

public boolean matches(String regex)
Varun
+5  A: 
Pattern p = Pattern.compile("/[^a-z0-9 ]/gi");
Matcher m = p.matcher("I am a string");
boolean b = m.matches();

if (b == true)
   System.out.println("There is a special character in my string");
r3zn1k
you need to import the correct Matcher and Pattern.import java.util.regex.Matcher;import java.util.regex.Pattern;This code is great for telling of the string passed in contains only a-z and 0-9, it won't give you a location of the 'bad' character or what it is, but then the question didn't ask for that.I feel regex is great skill for a programmer to master, I'm still trying.
jeff porter
A: 

can you explain me about that pattern class

TbmBizz
The javadocs do this, see http://www.j2ee.me/javase/6/docs/api/java/util/regex/Pattern.html
vickirk
java.lang.Pattern is a standard Java library for pattern matching (using regular expressions)
Epsilon Prime