Reputation: 11843
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
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