【问题标题】:stringr package str_extract() with inversion of the regex带有正则表达式反转的 stringr 包 str_extract()
【发布时间】:2015-08-28 17:52:59
【问题描述】:

我有一个如下字符串: 14ed0d69fa2.bbd.7f5512.filter-132.21026.55B67C8E27.0

以下正则表达式提取以点和数字结尾的最后一部分。我想提取除那部分之外的所有内容,但似乎找不到反转正则表达式的方法(使用 ^)没有帮助:

> s <- '14ed0d69fa2.bbd.7f5512.filter-132.21026.55B67C8E27.0'
> str_extract(s, '(\\.[0-9]{1})$')
[1] ".0"

我希望输出是:

[1] 14ed0d69fa2.bbd.7f5512.filter-132.21026.55B67C8E27

为了进一步澄清,我希望它按原样返回字符串,如果它不以点和一个数字结尾。

以下示例:

> s <- '14ed0d69fa2.bbd.7f5512.filter-132.21026.55B67C8E27'
> str_extract(s, someRegex)
[1] "14ed0d69fa2.bbd.7f5512.filter-132.21026.55B67C8E27"
> s <- '14ed0d69fa2.bbd.7f5512.filter-132.21026.55B67C8E27.1'
> str_extract(s, someRegex)
[1] "14ed0d69fa2.bbd.7f5512.filter-132.21026.55B67C8E27"
> s <- '14ed0d69fa2.bbd.7f5512.filter-132.21026.55B67C8E27.4'
> str_extract(s, someRegex)
[1] "14ed0d69fa2.bbd.7f5512.filter-132.21026.55B67C8E27"

【问题讨论】:

    标签: regex r stringr


    【解决方案1】:

    试试这个正则表达式:

    ^.*(?=\.\d+$)|^.*
    

    Regex live here.

    【讨论】:

    • 我可以编辑问题,但我不希望它截断最后一个 '.' 之后以多于一位数结尾的任何内容
    • @user3949008。很抱歉。
    【解决方案2】:

    一个选项是替换最后一位,

    sub("\\.\\d$", '', s)
    

    【讨论】:

      【解决方案3】:
      str_extract(s, ([\w ]+(?:\.|\-)){7})
      

      然后你可以访问返回的字符串到它的长度为 1,它会给你所需的输出!

      PS:您可能必须使用转义字符。

      【讨论】:

        【解决方案4】:

        例如,您可以使用stringr::str_remove()

        s <- '14ed0d69fa2.bbd.7f5512.filter-132.21026.55B67C8E27.0'
        stringr::str_remove(s, '(\\.[0-9]{1})$')
        #> [1] "14ed0d69fa2.bbd.7f5512.filter-132.21026.55B67C8E27"
        

        【讨论】:

          猜你喜欢
          • 2022-01-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-09-06
          • 1970-01-01
          • 1970-01-01
          • 2012-02-13
          • 1970-01-01
          相关资源
          最近更新 更多