Regexp Replace - Append String to Second Occurrence Using R's Sub

末鹿安然 提交于 2020-01-25 20:53:30

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!