【问题标题】:Replacing captured group with some added lettersReplacing captured group with some added letters
【发布时间】:2022-12-01 20:19:30
【问题描述】:

I would like to replace the captured group from my regex with XXX(captured group), but it is only replacing it with XXX and deleting the word captured by the regex.

search <- "[a-z]{5,}"
gsub((search), "xxx\\1", texts$text)

If the word: "wonderful" is matched by the regex, I would have wanted to replace it with "XXXwonderful", but I only got "XXX"

【问题讨论】:

    标签: r regex replace gsub capture-group


    【解决方案1】:

    You can use

    text <- "wonderful"
    
    search <- "\b([a-z]{5,})\b"
    gsub(search, "XXX\1", text, perl=TRUE)
    # => [1] "XXXwonderful"
    

    Or, if you have fully Unicode words:

    search <- "\b(\p{L}{5,})\b"
    gsub(search, "XXX\1", text, perl=TRUE)
    # => [1] "XXXwonderful"
    

    【讨论】:

      猜你喜欢
      • 2022-12-19
      • 2020-08-02
      • 2017-03-22
      • 2021-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多