Take the 2-minute tour ×

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 ("") 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").

share|improve this question
is the string length and format going to change every time? If not, you can just use substring() for this. –  tcash21 Oct 15 '13 at 14:17
As @tcash21 said... what are the rules for performing a regex? –  Simon O'Hanlon Oct 15 '13 at 14:18
I google for "regular expression in R" and in 1st got regular-expressions.info/rlanguage.html. Check if it answer your doubts. If so please delete this question. –  Marek Oct 15 '13 at 14:28
Thanks for your comment. Thats a reason I have posted the question. I have read a lot of solutions and rules but now my ideas are confused. For instance I have not considered substring() as a solution. Now I am trying to write the code using that function –  Jack Oct 15 '13 at 14:35
@TO THE DOWNVOTER: Granted this is not a "stellar SO Question", but please have a look at the person's rep before downvoting. Downvoting someone's first question is borderline obnoxious –  Ricardo Saporta Oct 15 '13 at 15:09

1 Answer 1

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


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.

share|improve this answer

Your Answer


