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

And do something like `[0-9]+` on the string `"aaa12xxx"` 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", "aaa12xxx")
[1] "aaaxxx"

```

But I got some form of response doing:

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

```

There's a small detail I'm missing.

Answer: 
It is probably a bit hasty to say '*ignore the standard functions*' - the help file for `?gsub` even specifically references in 'See also':

> 
> ‘regmatches’ for extracting matched substrings based on the results of
>  ‘regexpr’, ‘gregexpr’ and ‘regexec’.
> 
> 
> 

So this will work, and is fairly simple:

```
txt <- "aaa12xxx"
regmatches(txt,regexpr("[0-9]+",txt))
#[1] "12"

```
You can use PERL regexs' lazy matching:

```
> sub(".*?([0-9]+).*", "\\1", "aaa12xx99",perl=TRUE)
[1] "12"

```

Trying to substitute out non-digits will lead to an error in this case.