2

I'm working on Android Java application using regex. I'm trying to validate a sentence like: "I want a xxx pizza" by using a pattern like "I want a (TYPEA|TYPEB|TYPEC) pizza".

An example: I set the pattern to "I want a (salami|mushrooms|cheese) pizza" user inputs: "I want a salami pizza" the sentence is matched correctly and group(1) equals to "salami". But if the user inputs: "I want a capricciosa pizza" the whole matcher fails instead of just the group(1). Can the regex being modified in way to avoid the matcher to fail on the whole sentence and make it just to get a null-group at group(1) position?

Hope my explanation is clear.... thanks in advance.

1 Answer 1

2

Either the entire string is accepted or the entire string is rejected.

If you want a null group if the type of pizza does not match salami|mushrooms|cheese you could do

"I want a (?:(salami|mushrooms|cheese)|(?:.*)) pizza"

(?: ...) is a non-capturing group. And the |(?:.*) would be a "match anything escape hatch" to allow the entire string to be accepted (but still making group(1) null).

Demo:

Pattern p = Pattern.compile("I want a (?:(salami|mushrooms|cheese)|(?:.*)) pizza");

String[] tests = { "I want a salami pizza", "I want a shrimp pizza" };

for (String s : tests) {
    Matcher m = p.matcher(s);
    if (m.matches()) {
        System.out.println(s + ": " + m.group(1));
    }
}

Output:

I want a salami pizza: salami
I want a shrimp pizza: null
Sign up to request clarification or add additional context in comments.

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.