0

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.

3 Answers 3

1

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?

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.