代码之家  ›  专栏  ›  技术社区  ›  Tyler Rinker DaniM

带子组的组的编号后向引用

  •  3
  • Tyler Rinker DaniM  · 技术社区  · 7 年前

    gsub(
        "(((s?he( i|')s)|((you|they|we)( a|')re)|(I( a|')m)).{1,20})(\\b[Ff]an)(s?\\b)", 
        '\\1\\2atic\\3', 
        'He\'s the bigest fan I know.', 
        perl = TRUE, ignore.case = TRUE
    )
    
    ## [1] "He's the bigest He'saticHe's I know."
    

    (stuff before fan)(fan)(s\\b) 在伪代码中。

    我知道我的正则表达式可以替换所有的组,我知道它是有效的。只是反向参考部分。

    gsub(
        "(((s?he( i|')s)|((you|they|we)( a|')re)|(I( a|')m)).{1,20})(\\b[Ff]an)(s?\\b)", 
        '', 
        'He\'s the bigest fan I know.', 
        perl = TRUE, ignore.case = TRUE
    )
    
    ## [1] " I know."
    

    ## [1] "He's the bigest fanatic I know."
    

    匹配示例

    inputs <- c(
        "He's the bigest fan I know.",
        "I am a huge fan of his.",
        "I know she has lots of fans in his club",
        "I was cold and turned on the fan",
        "An air conditioner is better than 2 fans at cooling."
    )
    
    
    outputs <- c(
        "He's the bigest fanatic I know.",
        "I am a huge fanatic of his.",
        "I know she has lots of fanatics in his club",
        "I was cold and turned on the fan",
        "An air conditioner is better than 2 fans at cooling."
    )
    
    1 回复  |  直到 7 年前
        1
  •  4
  •   Wiktor Stribiżew    7 年前

    我知道你很难抓到过多的人。把你不感兴趣的东西变成 non-capturing 或删除那些明显多余的:

    ((?:s?he(?: i|')s|(?:you|they|we)(?: a|')re|I(?: a|')m).{1,20})\b(Fan)(s?)\b
    

    看到了吗 regex demo

    [Ff] 可以变成 F f 既然你在开玩笑 ignore.case=TRUE

    R demo :

    gsub(
        "((?:s?he(?: i|')s|(?:you|they|we)(?: a|')re|I(?: a|')m).{1,20})\\b(fan)(s?)\\b", 
        '\\1\\2atic\\3', 
        inputs, 
        perl = TRUE, ignore.case = TRUE
    )
    

    输出:

    [1] "He's the bigest fanatic I know."                     
    [2] "I am a huge fanatic of his."                         
    [3] "I know she has lots of fans in his club"             
    [4] "I was cold and turned on the fan"                    
    [5] "An air conditioner is better than 2 fans at cooling."