Reputation: 3461
I have a simple vector:
library(stringr)
a <- paste0("S", str_pad(1:360, 3, pad = "0"))
b <- sample(a, 180)
I want to remove all leading "S", "S0", "S00" in b
. How to do that?
Upvotes: 1
Views: 51
Reputation: 2589
In this case since you want to remove a string easily described by the regular expression S|S0+
you can use sub
(from base R
) or since you're using stringr
you could use str_replace
:
str_replace(b, "S|S0+", "")
There are going to be lots of regular expressions that will do the same job here, at least for the example given.
The one that most accurately describes what OP wants in general is ^S0*
given in another answer.
Upvotes: 1
Reputation: 70266
I suggest
sub("^S0*", "", b)
It will replace all S at the beginning of the string and 0+ number of zeros following the S. It won't accidentally remove an S in the middle of the string.
Note that this would also replace S000
at the beginning. If you want to limit it to maximum two zeros after the initial S, you can use
sub("^S0{0,2}", "", b)
Upvotes: 3
Reputation: 712
You can use this set of regular expressions:
sub("^0","", sub("^0" , "", sub("^S", "", b)))
Upvotes: 1