How to write optional word in Regular Expression?

自古美人都是妖i 提交于 2019-12-10 16:27:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!