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 capturing parentheses in the regular expression and group references in the replacement. Anything in parentheses gets remembered. Then they're accessed by \2, the first item. The first backslash escapes the backslash's interpretation in R so that it gets passed to the regular expression parser.

```
gsub('([[:alpha:]]+)([0-9]+)([[:alpha:]]+)', '\\2', "aaa12xxx")

```
Using the package *unglue* we would do the following: 

```r
# install.packages("unglue")
library(unglue)
unglue_vec(c("aaa12xxx", "aaaARGH!xxx"), "{prefix}{number=\\d+}{suffix}", var = "number")
#> [1] "12" NA

```

Created on 2019-11-06 by the [reprex package](https://reprex.tidyverse.org) (v0.3.0)

Use the `convert` argument to convert to a number automatically : 

```
unglue_vec(
  c("aaa12xxx", "aaaARGH!xxx"), 
  "{prefix}{number=\\d+}{suffix}", 
  var = "number", 
  convert = TRUE)
#> [1] 12 NA

```