Extract a regular expression match in R version 2.10

Posted by tovare on Stack Overflow See other posts from Stack Overflow or by tovare
Published on 2010-02-03T13:49:24Z Indexed on 2010/06/14 4:22 UTC
Read the original article Hit count: 276

Filed under:
|

Hi,

I'm trying to extract a number from a string.

And do something like this [0-9]+ on this string "aaaa12xxxx" and get "12".

I thought it would be something like:

> grep("[0-9]+","aaa12xxx", value=TRUE)
[1] "aaa12xxx"

And then I figured...

> sub("[0-9]+", "\\1", "aaa12xxxx")
[1] "aaa12xxx"

But I got some form of response doing:

> sub("[0-9]+", "ARGH!", "aaa12xxxx")
[1] "aaaARGH!xxx"

There's a small detail I'm missing Please advice :-)

I'm using R version 2.10.1 (2009-12-14)

Thanks !


Comments on the solution

The best solution is to ignore the standard functions and install Hadley Wickham's stringr package to get something that actually makes sense.

Kudos to Marek for figuring out how the standard library worked.

© Stack Overflow or respective owner

Related posts about regex

Related posts about r