gpt4 book ai didi

regex - R 正则表达式 : remove times from character string

转载 作者:行者123 更新时间:2023-12-04 19:05:49 24 4
gpt4 key购买 nike

我试图从字符串中删除/提取时间。逻辑是我正在捕获以下内容:

  • 必须以 0-2 位数字开头
  • 后面必须跟一个冒号
  • 后面可以跟冒号或句点,但不必
  • 可能后跟 1-无穷大数字(如果前一个条件为真)

  • 这是一个 MWE 和我尝试过的。我快到了,但我不想要 "6:33."被提取,而是 "6:33"因为冒号或逗号的出现必须后跟 1 个或多个数字。在这种情况下,句号是句子的结尾而不是时间的一部分。
    text.var <-  c("R uses 1:5 for 1, 2, 3, 4, 5.", 
    "At 3:00 we'll meet up and leave by 4:30:20.",
    "We'll meet at 6:33.", "He ran it in :22.34.")

    pattern <- "\\(?[0-9]{0,2}\\)?\\:\\(?[0-9]{2}\\)?\\(?[:.]{0,1}\\)?\\(?[0-9]{0,}\\)?"

    regmatches(text.var, gregexpr(pattern, text.var, perl = TRUE))

    ## [[1]]
    ## character(0)
    ##
    ## [[2]]
    ## [1] "3:00" "4:30:20"
    ##
    ## [[3]]
    ## [1] "6:33."
    ##
    ## [[4]]
    ## [1] ":22.34"

    期望输出
    ## [[1]]
    ## character(0)
    ##
    ## [[2]]
    ## [1] "3:00" "4:30:20"
    ##
    ## [[3]]
    ## [1] "6:33"
    ##
    ## [[4]]
    ## [1] ":22.34"

    最佳答案

    如果我理解正确,您可以使用以下方法来解决您的问题。

    regmatches(text.var, gregexpr('\\d{0,2}:\\d{2}(?:[:.]\\d+)?', text.var, perl=T))

    说明 :
    \d{0,2}   # digits (0-9) (between 0 and 2 times)
    : # ':'
    \d{2} # digits (0-9) (2 times)
    (?: # group, but do not capture (optional):
    [:.] # any character of: ':', '.'
    \d+ # digits (0-9) (1 or more times)
    )? # end of grouping

    备注 :我删除了转义的括号,因为我不清楚为什么首先使用它们。

    关于regex - R 正则表达式 : remove times from character string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25111074/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com