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: 
Use the new stringr package which wraps all the existing regular expression operates in a consistent syntax and adds a few that are missing:

```
library(stringr)
str_locate("aaa12xxx", "[0-9]+")
#      start end
# [1,]     4   5
str_extract("aaa12xxx", "[0-9]+")
# [1] "12"

```
One important difference between these approaches the the behaviour with any non-matches. For example, the regmatches method may not return a string of the same length as the input if there is not a match in all positions

```
> txt <- c("aaa12xxx","xyz")

> regmatches(txt,regexpr("[0-9]+",txt)) # could cause problems

[1] "12"

> gsub("[^0-9]", "", txt)

[1] "12" ""  

> str_extract(txt, "[0-9]+")

[1] "12" NA  

```