【问题标题】:Remove specific last character from string从字符串中删除特定的最后一个字符
【发布时间】:2017-07-24 03:10:06
【问题描述】:

我有以下字符串向量:

 EC02   502R   603           515    602   
 KL07   601    511R   505R   506R   503   
 508    514    501    509R   510    501R  
 512R   516    507    604    502    601R  
 SPK01  504    504R   ACK01  503R   508R  
 507R   ACK03  513    EC01   506    ECH01 
 ACK02  SPK02  509    511    512    505   
 KA01   RS01   510R   SKL01  SPK03  603R  
 602R   604R   513R   AECH01 ER03   AECH02
 RS02   514R   ER01   RH01   AR05   RH02  
 515R   ER02   M01 

我想替换502R to 502, 501R to 501, 503R to 503等等...

只有出现在字符串末尾的字符R 必须被替换。

我该如何使用gsub

【问题讨论】:

标签: r regex gsub


【解决方案1】:

如果您有一个字符串向量并想从中替换最后一个R 字符,您可以使用sub$ 这里确保 R 是向量中的最后一个字符。

sub("R$", "", str)

#[1] "EC02"  "502"   "603"   "5RFRS"

数据

str <- c("EC02", "502R","603", "5RFRS)

我在这里使用了sub 而不是gsubsub 只替换第一次出现的模式,而gsub 替换所有出现的模式,尽管在这种情况下sub/gsub 的使用无关紧要。

【讨论】:

    【解决方案2】:
    lapply( dfrm, function(col_) {gsub( "R","",col_)} )
    

    【讨论】:

    • 为什么是lapply,为什么是gsub而不是sub(好吧,OP指定gsub)? gsubsub 处理向量。 sub 以“R$”作为搜索字符串(根据 cmets 中的 @Ronak Shah)更具体地对我来说似乎更好。
    • @rosscova 我认为,示例向量的呈现方式在我看来就像一个数据框,因此是这个解决方案。
    【解决方案3】:

    如果要删除字符串末尾特定字符的所有次出现,您可能需要使用

    x <- c("EC02", "502R", "603RR")
    sub("R+$", "", x)
    # => [1] "EC02" "502"  "603" 
    trimws(x, which="right", whitespace="R+")
    # => [1] "EC02" "502"  "603" 
    

    请参阅R demo注意事项

    • sub("R+$", "", x) - 一个或多个 (+) R 字符串末尾的字母 ($) 匹配一次(sub 仅匹配模式的第一次出现)并将它们替换为空字符串
    • trimws(x, which="right", whitespace="R+") - 一个或多个 Rs (R+) 在字符串的末尾匹配 (which="right") 并被删除(trimws 基本上是在后台使用 sub)。

    注意 2:如果您打算以这种方式删除特殊的正则表达式元字符,则需要转义它们。需要转义的字符是:

    $^*()+\[{.?
    

    例如:

    sub("\\$+$", "", x) # Remove all $ chars at the end of string
    sub("\\^+$", "", x) # Remove all ^ chars at the end of string
    sub("\\(+$", "", x) # Remove all ( chars at the end of string
    sub("\\)+$", "", x) # Remove all ) chars at the end of string
    sub("\\++$", "", x) # Remove all + chars at the end of string
    sub("\\[+$", "", x) # Remove all [ chars at the end of string
    sub("\\{+$", "", x) # Remove all { chars at the end of string
    sub("\\.+$", "", x) # Remove all . (dot) chars at the end of string
    sub("\\?+$", "", x) # Remove all ? chars at the end of string
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-13
      • 1970-01-01
      • 2017-08-19
      • 2011-01-19
      • 2011-12-15
      相关资源
      最近更新 更多