jaywalker
jaywalker

Reputation: 1146

Java - Escaping + character in RegEx

My code is :

if (tokens.matches("true || false")){
            checkAssignments (i+1);
            return;
}
else{
    \\do something else
}

In this code fragment, the value of token is set to 'true' by default. But the control always goes to the else part implying that the regular expression evaluates to false.

Moreover, If i want to check for the presence of the character '+' in my string, what would my regular expression be in Java. I tried :

token.matches(\\+);

and

token.matches(\\Q+\\E);

but none of these work. Any help would be really appreaciated.

Upvotes: 0

Views: 107

Answers (3)

Sabuj Hassan
Sabuj Hassan

Reputation: 39443

matches() perform matching over the whole string with your regex. It doesn't check part of it.

For example:

 "this+this".matches("\\+"); // returns false

 "+".matches("\\+"); // returns true

 "this+this".matches(".*\\+.*"); // returns true

Upvotes: 1

Rohit Jain
Rohit Jain

Reputation: 213391

But the control always goes to the else part implying that the regular expression evaluates to false.

Notice that you've a trailing whitespace after true in your regex. That is not ignored. It will match a string "true ", with space at the end. Also, || is not an OR in regex. It is just a pipe - |.

So this will work fine:

if (token.matches("true|false")) { 
    checkAssignments (i+1);
    return;
} else {
    // do something else
}

If i want to check for the presence of the character '+' in my string, what would my regular expression be in Java.

Why do you need regex for that, instead of using String#contains() method?

Upvotes: 1

Christian Tapia
Christian Tapia

Reputation: 34176

To select between several alternatives, allowing a match if either one is satisfied, use the pipe "|" symbol to separate the alternatives:

if (tokens.matches("true|false")) {
    // ...
}

To check if your String contains +, you can use the following regex:

if (string.matches(.*\\+.*)) { ... }

Upvotes: 1

Related Questions