Jack
Jack

Reputation: 305

How to use regular expression in R working on a string

I'm trying to use regular expression in R. I'm pretty new with this language, sorry for this basic question. I'm working on this string ("11.22.33.44") and I would take just a part of that ("11.22.33"). I would delete (".44") and add on 55 to get as result ("11.22.3355").

Upvotes: 1

Views: 154

Answers (1)

IRTFM
IRTFM

Reputation: 263471

s <- "11.22.33.44"
sub("([[:digit:]]*\\.[[:digit:]]*\\.[[:digit:]]*)(\\.[[:digit:]]+)", "\\1", s)
#[1] "11.22.33"

?regex

Uses parentheses to demarcate two different patterns and return only the section that matched the first pattern. The first pattern is any number of digits separated by two periods. The periods need to be escaped (twice) in the first argument to any of the regex functions.

The "\\1" in the second argument is an example of reference to the first pattern. Those backslashes in the second argument are not really escapes in the same manner as the ones in the first argument.

Upvotes: 2

Related Questions