tags:

views:

195

answers:

5

Hi I want to validate a string which donot have numeric characters.

If my string is "javaABC" then it must be validated If my string is "java1" then it must not be validated

I want to restrict all the integers.

So how can I restrict using regex in java

Thanks Sunil Kumar Sahoo

+1  A: 

You can use this:

\D

"\D" matches non-digit characters.

Igor Oks
+1  A: 

More detail is here: http://java.sun.com/javase/6/docs/api/java/util/regex/Pattern.html

andy boot
+4  A: 

Try this:

String  Text        = ...;
boolean HasNoNumber = Text.matches("^[^0-9]*$");

'^[^0-9]*$' = From Start(^) to end ($), there are ([...]) only non(^) number(0-9). You can use '\D' as other suggest too ... but this is easy to understand.

See more info here.

NawaMan
Perhaps it's easier for a regexp newbie to understand hasDigits = Text.matches("[0-9]") ?
Brian Agnew
You are absolutely right!!! :D
NawaMan
"^\\D*$" is a shorter form ;)
Superfilin
@Brian: `Text.matches("[0-9]")` means "Text" consists of exactly one digit; you would need to say `Text.matches("(?s).*[0-9].*")` -- Java's funny that way. OTOH, @NawaMan's regex doesn't really need the anchors: `Text.matches("[^0-9]*")` or `Text.matches("\\D*")` work just fine.
Alan Moore
+1  A: 

The easiest to understand is probably matching for a single digit and if found fail, instead of creating a regexp that makes sure that all characters in the string are non-digits.

Thorbjørn Ravn Andersen
A: 

Here is one way that you can search for a digit in a String:

public boolean isValid(String stringToValidate) {
   if(Pattern.compile("[0-9]").matcher(stringToValidate).find()) {
       // The string is not valid.
       return false;
   }

   // The string is valid.
   return true;
}
hoffmandirt