【问题标题】:How to write optional word in Regular Expression?如何在正则表达式中编写可选单词?
【发布时间】:2015-12-10 12:44:12
【问题描述】:

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

我试过了:

abc def (the)? ghi

但是,它无法识别第二种模式。我哪里出错了?

【问题讨论】:

    标签: java regex regex-lookarounds


    【解决方案1】:
    abc def (the )?ghi
    
               ^^
    

    去掉多余的space

    【讨论】:

    • 非常感谢!!我花了将近一天的时间。
    • 说“谢谢”的最佳方式是将这个答案标记为已接受
    • java 正则表达式在任何意义上都不同于普通的正则表达式。忍受我的无知。我问这个是因为你的解决方案在这里工作。 regexr.com 。但不是当我为 java 正则表达式写作时。所以,这就是我所做的 abc def (\sthe)?ghi。这仅在不存在时才有效。
    • @vks 我写了 abc def(\\sthe)?ghi .still 同样的结果。我没听错吗?
    • @anil 它应该是abc def(\\sthe)? ghi
    【解决方案2】:

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

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

    只能匹配

    abc def the ghi
           ^   ^---spaces
    

    或者当我们删除the这个词时

    abc def  ghi
           ^^---spaces
    

    你需要像abc def( the)? ghi 这样的东西来使这些空格之一成为可选的。

    【讨论】:

      【解决方案3】:

      您的示例在 Python 中非常适合我

          x = "def(the)?"
          s = "abc def the ghi"
          res = re.search(x, s)
      

      返回:res -> 记录

          s = "abc def ghi"
          res = re.search(x, s)
      

      返回:res -> 记录

          s = "abc Xef ghi"
          res = re.search(x, s)
      

      返回:res -> 无

      【讨论】:

        猜你喜欢
        • 2015-12-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-09-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多