Pattern Matching and Replacement

Download r eBook

Introduction

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

Syntax

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

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

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

Remarks

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

Related Examples

Stats

546 Contributors: 15
Saturday, May 27, 2017
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial: info@zzzprojects.com

Download eBook