How do I make a regex that optionally matches a word in a string? For example, let's say I have a regex to match the sentence:
I like vanilla ice cream.
but I want that "vanilla" word to be optional so the same regex also matches
I like ice cream.
How do I do it? I've been using (vanilla)? but that doesn't seem to be working.
Not only does the word vanilla need to be optional, but also the white space that follows, i.e., (vanilla )?:
String s1 = "I like vanilla icecream";
String s2 = "I like icecream";
Pattern p = Pattern.compile("I like (vanilla )?icecream");
System.out.println(p.matcher(s1).matches()); // true
System.out.println(p.matcher(s2).matches()); // true
Try this
I like (vanilla )?ice cream
You probably forgot that extra space after "vanilla".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With