问题
I'm trying to append a string to the second occurance. The below code will replace the second occurrence with a static replacement string, but I need it to be flexible because the match can be, for example, either (cat|dog)
. Below is what I'm using to replace with a static string fish
.
string <- "xxx cat xxx cat xxx cat"
sub('^((.*?cat.*?){1})cat', "\\1\\fish", string, perl=TRUE)
[1]'xxx cat xxx fish xxx cat'
But what I'm trying to get is:
string <- "xxx cat xxx cat xxx cat"
sub('^((.*?(cat|dog).*?){1})(cat|dog)', "\\1<span>\\1</span>", string, perl=TRUE)
[1] xxx cat xxx <span>cat</span> xxx cat
or
string <- "xxx dog xxx dog xxx dog"
sub('^((.*?(cat|dog).*?){1})(cat|dog)', "\\1<span>\\1</span>", string,
[1] xxx dog xxx <span>dog</span> xxx dog
回答1:
This is probably not the most efficient or concise regex but I find it easier to understand this way:
sub('^(.*?)(cat|dog)(.*?)(cat|dog)', '\\1\\2\\3<span>\\4</span>', string, perl=TRUE)
The {1}
in your regex is not needed. With your syntax (nested capturing groups) but without the {1}
, here is what you could use:
sub('^(.*?(cat|dog).*?)(cat|dog)', '\\1<span>\\3</span>', string, perl=TRUE)
Note that those regex do not check that the same word (car or dog) is matched both times.
来源:https://stackoverflow.com/questions/43396526/regexp-replace-append-string-to-second-occurrence-using-rs-sub