Mark Tickner
Mark Tickner

Reputation: 1053

Checking for ^ character in java string

I want to check a string to see if it contains the ^ symbol, and if it does display a message to the user.

Thanks

Pattern p = Pattern.compile("[a-z0-9 ]", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher("StringGoesHere");
boolean b = m.find();

if (b){
   System.out.println("bad");
} else {
   System.out.println("fine");
}

Upvotes: 0

Views: 343

Answers (4)

Has QUIT--Anony-Mousse
Has QUIT--Anony-Mousse

Reputation: 77454

Actually, the simplest answer would be: don't use an regexp, just search for the character itself.

The longer answer is: see the details of the regular expression syntax on escaping.

In charcter classes, ^ is only special if it is the first symbol. So [a-z^] will match any of a-z or ^, while [^a-z] matches everything except a-z (since ^ as first character is negation).

Outside of a character class, ^ matches the beginning of the line, unless you escape it with \. And for Java inline strings, you need to write that as "\\^".

Upvotes: 1

The Real Baumann
The Real Baumann

Reputation: 1961

Why not just

String str = "StringGoesHere";
if( str.indexOf('^') != -1 )
{
    System.out.println( "bad" );
}
else
{
    System.out.println("fine");
}

Upvotes: 10

amit
amit

Reputation: 178431

a regex might be an overkill, just use String.contains()

If you are eager to use a regex, use "\\^": \\ will provide a single \, which is breaking the special meaning of the ^ char.

Upvotes: 15

erickson
erickson

Reputation: 269657

Pattern p = Pattern.compile("\\^");

Upvotes: 1

Related Questions