问题
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?
回答1:
abc def (the )?ghi
^^
Remove the extra space
回答2:
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.
来源:https://stackoverflow.com/questions/32566087/how-to-write-optional-word-in-regular-expression