Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing the last trailing underscore from a string

Tags:

string

r

gsub

I am trying to remove the last trailing underscore(_) from a string using R.

For example,

  Col1
  TX_
  AZ_TX
  CA_LX
  CHI_
  KS_

The above strings should look like

  Col1
  TX
  AZ_TX
  CA_LX
  CHI
  KS

Only the trailing _ be gone. I tried sub("_", "", my_dataframe$my_column) but this removes all the _ from the string. I am just looking for a function that removes the last trailing _ and not all. Any ideas ?

like image 694
Kim Jenkins Avatar asked Oct 02 '16 12:10

Kim Jenkins


People also ask

How do I remove a trailing character from a string?

Trim(char) removes the leading and trailing occurrences of the input character from a string and returns a new string. Each leading and trailing trim operation is stopped when a character other than the input character is encountered.

How do you remove underscore from a string?

To remove the underscores from a string, call the replaceAll() method on the string, passing it an underscore as the first parameter, and an empty string as the second, e.g. replaceAll('_', '') . The replaceAll method will return a new string, where all underscores are removed. Copied!

How do you remove the underscore at the end of a string in Python?

Remove Character from String Python: replace() The replace() method removes the underscore character from the original string and replaces all instances of that character with an empty string.

How do I remove a trailing character in Java?

The deleteCharAt() method accepts a parameter as an index of the character you want to remove. Remove last character of a string using sb. deleteCharAt(str. length() – 1).


1 Answers

You can use sub (or gsub) with the regular expression "_$" to find the _ at the end of the input, then replace with "":

s <- c('Col1', 'TX_', 'AZ_TX', 'CA_LX', 'CHI_', 'KS_')
sub("_$","",s)
##[1] "Col1"  "TX"    "AZ_TX" "CA_LX" "CHI"   "KS"   
like image 79
aichao Avatar answered Sep 21 '22 05:09

aichao