zesla
zesla

Reputation: 11843

extract multiple numbers from a string and replace the whole string with a new string containing the numbers in r

I have a string like below:

s = 'regimen A1 Cycle 3 Day 5 treatment B1 '

what I need to do is replace the whole string as C3D5 (cycle 3 day 5). I wonder how to do that using regular expression? I tried:

str_replace(s, '.*Cycle\\s+(\\d+)Day\\s+(\\d+).*', 'C\\1D\\2' )

what I got is the original string. Could anyone tell me what I did wrong? Any elegant way to do that?

Upvotes: 0

Views: 29

Answers (1)

akuiper
akuiper

Reputation: 215137

Your regex is off - you missed a space between the first digit and Day, in which case the pattern doesn't match, so no replacement happens. Try:

str_replace(s, '.*Cycle\\s+(\\d+)\\s+Day\\s+(\\d+).*', 'C\\1D\\2' )
#                                ^^^^
# [1] "C3D5"

Upvotes: 1

Related Questions