【问题标题】:Find & replace a character in a particular position查找和替换特定位置的字符
【发布时间】:2016-07-28 06:57:07
【问题描述】:
Comment
(apple (a) 100)
(orange 50)



Comment1
apple (a) 100
orange 50

我需要使用 r 将开始的左括号和结束的右括号替换为 none。

我的数据样本在“评论”字段中。我的预期输出在“Comment1”字段中。

【问题讨论】:

    标签: regex r replace


    【解决方案1】:

    我们可以使用gsub匹配开头的括号(^\\()或结尾的括号(|)(\\)$),并替换为""。

    gsub("^\\(|\\)$", "", Comment)
    #[1] "apple (a) 100" "orange 50"    
    

    或者如果它基于位置,我们可以将需要的字符放在一个捕获组中,即在括号内 ((.*)) 并用反向引用 (\\1) 替换它。

    sub(".(.*).", "\\1", Comment)
    #[1] "apple (a) 100" "orange 50" 
    

    或者substring

    substring(Comment, 2, nchar(Comment)-1)
    #[1] "apple (a) 100" "orange 50"    
    

    数据

    Comment <- c("(apple (a) 100)","(orange 50)")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-10
      • 1970-01-01
      • 2017-09-17
      • 2015-10-18
      • 2011-01-15
      相关资源
      最近更新 更多