[R] regex sub with specified number of characters
David Winsemius
dwinsemius at comcast.net
Tue Oct 6 16:51:27 CEST 2015
On Oct 6, 2015, at 7:38 AM, Johannes Radinger wrote:
> Hi
>
> I'd like to remove a leading "3" if my number is 7 digits long, if it is
> only 6 I don't want to anything.
> I think this should be possible with a 1-liner using sub() but I am not
> sure how to define the number of characters following the leading one.
>
> For example my vector:
>
> a <- c(3593857,384723,4395843,3398374)
>
> with sub("^3","",a) I also remove the leading from the second element which
> is only 6 digits long. So how to restrict that using sub? The final result
> should be
>
> a <- c(593857,384723,4395843,398374)
Use a wild-card capture class of the correct length:
> sub("^3(.{6})$", "\\1", a)
[1] "593857" "384723" "4395843" "398374"
>
> [[alternative HTML version deleted]]
It doesn't affect this post but you are requested to post in plain text.
--
David Winsemius
Alameda, CA, USA
More information about the R-help
mailing list