Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expressions- Optionally Match a Word

Tags:

regex

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.

like image 232
Walker Avatar asked Dec 31 '25 18:12

Walker


2 Answers

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
like image 165
João Silva Avatar answered Jan 02 '26 09:01

João Silva


Try this

I like (vanilla )?ice cream

You probably forgot that extra space after "vanilla".

like image 41
Michael Hays Avatar answered Jan 02 '26 11:01

Michael Hays