Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove trailing punctuation from string

Tags:

regex

r

I am trying to delete all dashes that appear at the end of a string and my code is causing R to crash. Any tweaks or code fixes that might not cause this would be greatly appreciated!

acct_nm = str_replace_all(acct_nm, "[:punct:]+", "")

Right not I have this wrapped as part of a mutate, unfortunately I cannot show all of my code or include my data. Basically all I want it to replace the acct_nm variable with acct_nm - any trailing punctuation.

As an an example, I want it to work similar to the code below where the variable y gets all trailing punctuation deleted.

library(tidyverse)
test <- data.frame(x = 1:3, y = 'hello-./') %>% 
         mutate(z = str_replace_all(y, "[:punct:]+", ""))

enter image description here

like image 258
Alex Gouveia Avatar asked Sep 29 '26 07:09

Alex Gouveia


1 Answers

You can try using sub/gsub and remove punctuations at the end of string

sub('[[:punct:]]+$', '', test$y)
#[1] "-hello" "-hello" "-hello"

data

test <- data.frame(x = 1:3, y = '-hello-./')
like image 185
Ronak Shah Avatar answered Oct 01 '26 20:10

Ronak Shah