Reg ex Question

#1
Hi!

I have a string, that follows a predictable format, and I'm looking to replace certain characters in it. Please see below. Any help is appreciated.

Code:
> have <- "_a _a_1 _a_2 _a_3"
> have

[1] "_a _a_1 _a_2 _a_3"
What I need to do is remove the initial underscore in each space delimited chunk, while keeping any underscores in the string. E.g.

Code:
> want <- "a a_1 a_2 a_3"
> want

[1] "a a_1 a_2 a_3"
I have a list of 4-5 patterns that I've solved using {stringr} and / or gsub() and this is the only one I can't get. I realized I could break the string up into space delimited bits and use substr to cleave off the first character, but I'm wondering if there is a more elegant way?

Any help is appreciated!
 

Dason

Ambassador to the humans
#2
In regular expressions \b matches the beginning and end of a word i.e. space, tab or newline, or the beginning or end of a string. So in R we just need to escape that and then add the underscore and replace all of that with nothing.

Code:
x <- "_a _a_1 _a_2 _a_3"
gsub("\\b_", "", x)
#[1] "a a_1 a_2 a_3"
 
#3
In regular expressions \b matches the beginning and end of a word i.e. space, tab or newline, or the beginning or end of a string. So in R we just need to escape that and then add the underscore and replace all of that with nothing.

Code:
x <- "_a _a_1 _a_2 _a_3"
gsub("\\b_", "", x)
#[1] "a a_1 a_2 a_3"
Thank you for the quick reply, Dason!

You have no idea how much you've simplified my day... (after a very long and exhausting work week)
 

Dason

Ambassador to the humans
#4
I'm glad I could help. This kind of question is right in the sweet spot of questions that I'm willing to spend time answering these days.