Skip to content
Prev 393734 / 398506 Next

Minimal match to regexp?

grep(value = TRUE) just returns the strings which match the pattern. You
have to use regexpr() or gregexpr() if you want to know where the matches
are:

```
x <- "abaca"

# extract only the first match with regexpr()
m <- regexpr("a.*?a", x)
regmatches(x, m)

# or

# extract every match with gregexpr()
m <- gregexpr("a.*?a", x)
regmatches(x, m)
```

You could also use sub() to remove the rest of the string:
`sub("^.*(a.*?a).*$", "\\1", x)`
keeping only the match within the parenthesis.
On Wed, Jan 25, 2023, 19:19 Duncan Murdoch <murdoch.duncan at gmail.com> wrote: