如何在正则表达式中编写可选单词?

AV9*_*V94 4 java regex regex-lookarounds

我想编写一个识别以下模式的java Regular表达式. abc def the ghiabc def ghi

我试过这个:

abc def (the)? ghi
Run Code Online (Sandbox Code Playgroud)

但是,它没有认识到第二种模式.我哪里出错了?

vks*_*vks 7

abc def (the )?ghi

           ^^
Run Code Online (Sandbox Code Playgroud)

删除额外的 space

  • 说"谢谢"的最佳方式是将此答案标记为已接受 (4认同)
  • 非常感谢!!我在这上面花了将近一天的时间。 (2认同)

Psh*_*emo 5

空格也是正则表达式中的有效字符,因此

abc def (the)? ghi
       ^      ^ --- spaces
Run Code Online (Sandbox Code Playgroud)

只能匹配

abc def the ghi
       ^   ^---spaces
Run Code Online (Sandbox Code Playgroud)

或者当我们删除the单词时

abc def  ghi
       ^^---spaces
Run Code Online (Sandbox Code Playgroud)

abc def( the)? ghi还需要类似的东西来使这些空间之一成为可选的。