Reputation: 1814
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?
Upvotes: 16
Views: 13131
Reputation: 322
Your example worked perfectly well for me in Python
x = "def(the)?"
s = "abc def the ghi"
res = re.search(x, s)
Returns: res -> record
s = "abc def ghi"
res = re.search(x, s)
Returns: res -> record
s = "abc Xef ghi"
res = re.search(x, s)
Returns: res -> None
Upvotes: 0
Reputation: 124225
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.
Upvotes: 6