user1981275 user1981275 - 1 year ago 62
R Question

How to match multiple capture groups with str_match(..., regex)

I am using

from the
package to capture text in between brackets.


strs = c("P5P (abcde) + P5P (fghij)", "Glcext (abcdef)")
str_match(strs, "\\(([a-z]+)\\)")

gives me only the matches
. How can I capture the
as well with still using the same regex for both strings?

Answer Source
str_extract_all(strs, "\\(([a-z]+)\\)")

or as @JoshO'Brien mentions in his comment,

str_match_all(strs, "\\(([a-z]+)\\)")

This can just as easily be accomplished with base R:

regmatches(strs, gregexpr("\\(([a-z]+)\\)", strs))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download