In R, how to use regex to look for a PATTERN of strings?

Viewed 138

I am trying to replace a pattern in each row of my dataset with a single space.

The pattern is: MM/DD/YYYY ##:##:## Person Name (PNAME)

Each row is a string like:

[1] TEXT BEFORE... 04/17/2014 08:46:42 John Doe (JDOE) ...TEXT AFTER

Desired results:

[1] TEXT BEFORE... ...TEXT AFTER

I attempted it with the following (and many variations):

pattern <- "[[0-9]][[0-9]][[:punct:]][[0-9]][[0-9]][[:punct:]][[0-9]][[0-9]][[0-9]][[0-9]][[:space:]][[0-9]][[0-9]][[:punct:]][[0-9]][[0-9]][[:punct:]][[0-9]][[0-9]][[:space:]][[:alpha::]][[:space:]][[:alpha::]][[:punct:]][[:alpha::]][[:punct:]]) "
replacement <- " "

sub(pattern, replacement, data$Description)

It seems I am not setting the pattern correctly. I have read a number or regex questions on here but none that uses a pattern attempting to replace more than a single character/word. How would you write this?

1 Answers

There are several issues here:

  • [[0-9]] matches [ or a digit and then a ], you need just \d or [0-9] to match a digit
  • To match a letter you need [[:alpha:]] and not [[:alpha::]]
  • You do not need to manually type several [0-9] or [[:alpha:]], you can use + or limiting (range) quantifiers (like {1,2}).

You can use

gsub("\\s+\\d{1,2}/\\d{1,2}/\\d{4}\\s+\\d{1,2}:\\d{1,2}:\\d{1,2}\\s+\\w+\\s+\\w+\\s+\\([^()]*\\)", "", data$Description)

See the regex demo

Details

  • \s+ - one or more whitespaces
  • \d{1,2}/\d{1,2}/\d{4} - date-like string (one or two digits, /, one or two digits, /, four digits)
  • \s+ - one or more whitespaces
  • \d{1,2}:\d{1,2}:\d{1,2} - time-like string
  • \s+\w+\s+\w+\s+ - two whitespace separated words enclosed with one or more whitespaces (also, can be written as (?:\s+\w+){2}\s+)
  • \( - a ( char
  • [^()]* - zero or more chars other than ( and )
  • \) - a ) char.
Related