[R] how to implement string pattern extraction in R

Gabor Grothendieck ggrothendieck at gmail.com
Mon Aug 23 00:31:48 CEST 2010


On Sun, Aug 22, 2010 at 6:05 PM, Waverley @ Palo Alto
<waverley.paloalto at gmail.com> wrote:
> Hi,
>
> In perl, to get a substring matching a particular  pattern can be
> implemented like the following example:
>
> $x = "AAAA.txt";
> if ($x=~ /(.*?)\.txt/){
>  $prefix = $1;
> }
>
> So how to do the same thing in R?
>
> Can someone provide me the code sample?
>

Try any of these:

x <- "AAAA.txt"

# 1
sub("(.*)\\.txt", "\\1", x)

# 2
sub(".txt$", "", x)

# 3
strsplit(x, "\\.")[[1]][1]

#4
library(gsubfn)
strapply(x, "(.*)\\.txt", simplify = c)



More information about the R-help mailing list