I want to use stri_replace_all_regex to replace string but failed. I would like to know whether there are other methods to overcome it. Thanks for anyone who gives help to me!
try: the first:
> library(string)
> a <- c('abc2','xycd2','mnb345','tumb b~','lymavc')
> b <- c('ab','abc','xyc','mnb','tum','mn','tumb','lym','lymav')
> stri_replace_all_regex(a, "\\b" %s+% b %s+% "\\S+", b, vectorize_all=FALSE)
However, the result is :
> c("ab","xyc","mn" ,"tum b~","lym")
which is not I want. I want the result should be:
> c('abc','xyc','mnb','tumb','lymac')
the second:
> pattern <- paste0("\\b(", b, ")\\S+", collapse = "|")
> gsub(pattern, "\\w", a)
However it failed.
I feel sorry it's my mistake that I do not express clearly.
In fact, I want to replace b
with a
.
As you see, a
and b
have some similar parts on the left, I want to remove the difference from a
. But should be greedy match.
For example:
The result of 'tumb b~‘
should be 'thumb'
not 'tum'
and the result of 'mnb345‘
should be 'mnb'
not 'mn'
.
I just learn regex expresion, so my try may be complex and cumbersome. Looking forward for your reply!
A new questions occurs.
a <- c('tums310','tums310~20','tums320') b<-c('tums1','tums2','tums3')
I want the result should be
"tums3" "tums3" "tums3"