Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove nth occurrences of a character from string in R?

Tags:

r

I have the below character string.

"File-2022-03-08-S1-PAR-C-J1-SET"

How can I remove the second and third occurrences of the dash (-) symbol and keep all others? Essentially, I'd like the date (2023-03-08) to read 20230308.


2 Answers

Not sure but do you want result to be something like File-20220308-S1-PAR-C-J1-SET

if yes, then this can be achieved using :

string <- "File-2022-03-08-S1-PAR-C-J1-SET"

modifiedString <- gsub("-(\\d{4})-(\\d{2})-", "-\\1\\2", string)

modifiedString
like image 183
Manoj Kumar Avatar answered Oct 23 '25 18:10

Manoj Kumar


Using lookarounds.

> gsub(r"{-(?=\d{2}\D)}", "", "File-2022-03-08-S1-PAR-C-J1-SET", perl=TRUE)
[1] "File-20220308-S1-PAR-C-J1-SET"
like image 29
jay.sf Avatar answered Oct 23 '25 18:10

jay.sf