【问题标题】:Unexpected regular expression result in stringr (R)意外的正则表达式导致 stringr (R)
【发布时间】:2017-02-27 01:57:33
【问题描述】:

请有人向我解释一下,为什么 str_detect(来自 stringr 包,ver 1.1.0)对以下三个代码中的每一个都返回 TRUE,这与我的预期相反?

str_detect("01", "^[0]*[1-9]*[0]+")
str_detect("01", "^0*[1-9]*0+")
str_detect("01", "^0*[1-9]*0")

我想查找开头的任何零,后跟至少 1 个非零数字,然后是字符串中的零。

显然“01”字符串不能限定,因为它在 1 之后没有 0。

我错过了什么吗?我正在寻找的模式是否错误?

感谢您的宝贵时间!

【问题讨论】:

    标签: r regex string-matching stringr


    【解决方案1】:

    由于前导 0 在您的模式中是可选的,因此它们被忽略并且尾随零检测字符串中的 0...

    使用 $ 指定字符串的结尾:

    str_detect("01", "^[0]*[1-9]*[0]+$")
    str_detect("01", "^0*[1-9]*0+$")
    str_detect("01", "^0*[1-9]*0$")
    

    【讨论】:

      【解决方案2】:

      我相信你想要以下模式:

      ^0[1-9]+0
      

      请参阅https://regex101.com/r/v9cwHJ/1 了解完整的模式说明。
      您的具体错误是使用 * 作为前 0,它也不匹配。
      也可以使用 + 作为第二个数字来找到至少 1。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-09-27
        • 2012-07-16
        • 2018-09-06
        • 2020-06-27
        • 2022-01-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多