R Language Pattern Matching and Replacement

30% OFF - 9th Anniversary discount on Entity Framework Extensions until December 15 with code: ZZZANNIVERSARY9


This topic covers matching string patterns, as well as extracting or replacing them. For details on defining complicated patterns see Regular Expressions.


  • grep("query", "subject", optional_args)

  • grepl("query", "subject", optional_args)

  • gsub("(group1)(group2)", "\\group#", "subject")


Differences from other languages

Escaped regex symbols (like \1) are must be escaped a second time (like \\1), not only in the pattern argument, but also in the replacement to sub and gsub.

By default, the pattern for all commands (grep, sub, regexpr) is not Perl Compatible Regular Expression (PCRE) so some things like lookarounds are not supported. However, each function accepts a perl=TRUE argument to enable them. See the R Regular Expressions topic for details.

Specialized packages

Got any R Language Question?