【问题标题】:Regex-Creating consecutive words in a sentenceRegex-在一个句子中创建连续的单词
【发布时间】:2014-12-31 00:03:45
【问题描述】:

我有一个字符串:

t="abc,mno,pqr,xyz,qwe,asd"

我想要所有可能的 3 个连续单词作为输出,如下所示:

"abc mno pqr,mno pqr xyz,pqr xyz qwe,xyz qwe asd"

我使用的是 R,所以要使用 perl 正则表达式引擎。

有什么想法吗?

谢谢。

【问题讨论】:

    标签: regex r pcre


    【解决方案1】:

    好吧,我自己想通了,

    t="abc,mno,pqr,xyz,qwe,asd"
    t=gsub("(?=,([^,]*),([^,]*))", " \\1 \\2", t, perl=T)
    t=gsub("(,[^,]*,[^,]*)$", "", t, perl=T)
    t
    "abc mno pqr,mno pqr xyz,pqr xyz qwe,xyz qwe asd"
    

    【讨论】:

    【解决方案2】:

    这是一个非正则表达式可能的解决方案

    t <- "abc,mno,pqr,xyz,qwe,asd" 
    library(zoo)
    paste(rollapply(strsplit(t, ",")[[1]], width = 3, FUN = paste, collapse = " "), collapse = ",")
    ## [1] "abc mno pqr,mno pqr xyz,pqr xyz qwe,xyz qwe asd"
    

    【讨论】:

      【解决方案3】:

      另一个 gsub 方法,

      > t="abc,mno,pqr,xyz,qwe,asd"
      > m <- gsub("(?=,([^,]+),([^,]+)\\b(?!$))", " \\1 \\2", t, perl=TRUE)
      > result <- gsub(",(?=(?:[^,]*,)?[^,]*$)", " ", m, perl=TRUE)
      > result
      [1] "abc mno pqr,mno pqr xyz,pqr xyz qwe,xyz qwe asd"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-18
        • 2023-03-16
        • 1970-01-01
        • 2022-09-23
        • 1970-01-01
        相关资源
        最近更新 更多