【问题标题】:R extract substring from end of pattern until first occurance of characterR从模式末尾提取子字符串,直到第一次出现字符
【发布时间】:2014-03-15 19:56:12
【问题描述】:

苦苦挣扎了好几个小时才能获得这场比赛并替换 R gsub 工作,但仍然没有成功。 我正在尝试匹配字符串中的模式"Reason:",并在此模式之后提取所有内容,直到第一次出现点(.) 例如:

Offer Disposition. MSISDN: 7183067962. Offer: . Disposition: DECLINED. Reason: Not interested. ChannelID: CARE.

将返回"Not interested"

【问题讨论】:

    标签: regex r gsub


    【解决方案1】:

    这里有一个解决方案:

    s <- "Offer Disposition. MSISDN: 7183067962. Offer: . Disposition: DECLINED. Reason: Not interested. ChannelID: CARE."
    
    sub(".*Reason: (.*?)\\..*", "\\1", s)
    # [1] "Not interested"
    

    更新(针对 cme​​ts):

    如果您还有与模式不匹配的字符串,我建议使用regexpr 而不是sub

    s2 <- c("no match example",
            "Offer Disposition. MSISDN: 7183067962. Offer: . Disposition: DECLINED. Reason: Not interested. ChannelID: CARE.")
    
    match <- regexpr("(?<=Reason: ).*?(?=\\.)", s2, perl = TRUE)
    ifelse(match == -1, NA, regmatches(s2, match))
    # [1] NA                                "Not interested. ChannelID: CARE"
    

    对于第二个示例,您可以使用以下正则表达式:

    s3 <- "Delete Payment Arrangement of type Proof of Payment for BAN : 907295267 on date 02/01/2014, from reason PAERR."
    
    # a)
    sub(".*type (.*?) for.*", "\\1", s3)
    # [1] "Proof of Payment"
    
    # b)
    match <- regexpr("(?<=type ).*?(?= for)", s3, perl = TRUE)
    ifelse(match == -1, NA, regmatches(s3, match))
    # [1] "Proof of Payment"
    

    【讨论】:

    • 非常感谢。作品。但是,匹配条件为 FALSE(未找到模式“原因:”),将返回整个字符串。为什么以及如何避免这种情况(应返回 Null)?谢谢
    • 以及 - 如果匹配的 END 字符是单词(在我的情况下为“For”)而不是点 (.),您的代码将如何更改?这样从句子中:“删除 BAN 付款证明类型的付款安排:907295267 日期为 2014 年 2 月 1 日,原因为 PAERR。”正则表达式 sub(".*type (.*?)\\..*", "\\1", s) 将返回“type”和“for”第一次出现之间的字符串(即“付款证明” ) ?谢谢
    【解决方案2】:

    许多不同的方式(正如您从提交中看到的那样)。我个人喜欢使用stringr 函数。

    library(stringr)
    
    rec <- "Offer Disposition. MSISDN: 7183067962. Offer: . Disposition: DECLINED. Reason: Not interested. ChannelID: CARE."
    str_match(rec, "Reason: ([a-zA-Z0-9\ ]+)\\.")[2]
    ## [1] "Not interested"
    

    【讨论】:

      【解决方案3】:

      使用正则表达式和正则匹配:

      str <- "Offer Disposition. MSISDN: 7183067962. Offer: . Disposition: DECLINED. Reason: Not interested. ChannelID: CARE."
      m<-regexpr("(?<=Reason: )[^.]+", str, perl=TRUE)
      regmatches(str, m)
      

      【讨论】:

        【解决方案4】:

        这将起作用:

        x <- "Offer Disposition. MSISDN: 7183067962. Offer: . Disposition: DECLINED. Reason: Not interested. ChannelID: CARE."
        
        library(qdap)
        genXtract(x, "Reason:", ".")
        
        ##     Reason:  :  . 
        ## " Not interested" 
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-01-04
          • 1970-01-01
          • 1970-01-01
          • 2015-12-14
          • 1970-01-01
          • 1970-01-01
          • 2018-02-05
          • 1970-01-01
          相关资源
          最近更新 更多