【问题标题】:substitute complex regular expression in R替换R中的复杂正则表达式
【发布时间】:2021-08-12 20:43:24
【问题描述】:

我正在尝试使用 gsub 将文本替换为单词。例如:

我的文字是: 我会将 [USER=1234]@banana1[/USER] 添加到聊天中

我想要的输出是: 我会在聊天中添加用户名

基本上,我想替换 [USER=1234]@banana1[/USER] 到 用户提及

我尝试了以下代码但没有成功:


text=c("I ​will add [USER=1234]@banana1[/USER] to the chat")
replace_user=gsub("\\[user.*?\\/user\\]","usermention",text)

【问题讨论】:

    标签: r gsub


    【解决方案1】:

    你可以使用它

    > gsub("\\[user.*?/user]","usermention",text, ignore.case=TRUE)
    [1] "I ​will add usermention to the chat"
    

    请注意,/ 在 TRE 正则表达式模式中没有任何特殊之处,] 在括号表达式之外也是如此,因此无需转义。

    由于原始字符串中有USER 而不是user,因此您需要ignore.case=TRUE 参数。

    请参阅regex demo online。

    见R demo:

    text=c("I will add [USER=1234]@banana1[/USER] to the chat"
    gsub("\\[user.*?/user]","usermention",text, ignore.case=TRUE)
    ## => [1] "I will add usermention to the chat"
    

    【讨论】:

      【解决方案2】:

      我们可以使用

       sub("\\[.*\\]", "usermention", text)
      [1] "I ​will add usermention to the chat"
      

      【讨论】:

      • 您好,谢谢,我以前做过,但问题是还有其他类似于我需要替换的正则表达式,例如: [url]google.com/[/url] 到 urllink这就是我没有使用它的原因。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-09
      • 1970-01-01
      • 1970-01-01
      • 2015-02-21
      相关资源
      最近更新 更多