Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write optional word in Regular Expression?

I want to write a java Regular expression that recognises the following patterns. abc def the ghi and abc def ghi

I tried this:

abc def (the)? ghi

But, it is not recognizing the second pattern.Where am I going wrong?

like image 807
AV94 Avatar asked Sep 14 '15 13:09

AV94


2 Answers

abc def (the )?ghi

           ^^

Remove the extra space

like image 132
vks Avatar answered Oct 18 '22 01:10

vks


Spaces are also valid characters in regex, so

abc def (the)? ghi
       ^      ^ --- spaces

can match only

abc def the ghi
       ^   ^---spaces

or when we remove the word

abc def  ghi
       ^^---spaces

You need something like abc def( the)? ghi to also make one of these spaces optional.

like image 39
Pshemo Avatar answered Oct 17 '22 23:10

Pshemo