Escaped Periods In R Regular Expressions

Viewed 32608

Unless I am missing something, this regex seems pretty straightforward:

grepl("Processor\.[0-9]+\..*Processor\.Time", names(web02))

However, it doesn't like the escaped periods, \. for which my intent is to be a literal period:

Error: '\.' is an unrecognized escape in character string starting "Processor\."

What am I misunderstanding about this regex syntax?

3 Answers

Instead of

\.

Try

\\.

You need to escape the backspace first.

The R-centric way of doing this is using the [::] notation, for example:

grepl("[:.:]", ".")
# [1] TRUE
grepl("[:.:]", "a")
# [1] FALSE

From the docs (?regex):

The metacharacters in extended regular expressions are . \ | ( ) [ { ^ $ * + ?, but note that whether these have a special meaning depends on the context.

[:punct:] Punctuation characters: ! " # $ % & ' ( ) * + , - . / : ; < = > ? @ [ \ ] ^ _ ` { | } ~.

Related