简体   繁体   中英

Remove variable amounts of leading strings from values in a vector

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?

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)

您可以使用以下一组正则表达式:

sub("^0","", sub("^0" ,  "", sub("^S", "", b)))

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM