简体   繁体   中英

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.

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(.*\\+.*)) { ... }

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

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM