I have a vector of strings
c("a b c xxxxxx d", "1 3 4 xxx", "x y z")
And I hope to replace all xx…x with an empty space. So I am expecting to get the following after removal.
c("a b c d", "1 3 4 ", "x y z")
I did some search which suggests that string_replace_all( ) and grep( ) together can solve this problem. And I tried to use grep( ) to check if the first and last character is an "x". But I am not sure how to turn grep( ) into a pattern that can be used as an argument for string_replace_all( ).
Could anyone help?
Use the pattern xx+ (“at least two repetitions of “x”) and replace that with a space:
xx+
str_replace_all(text, 'xx+', ' ') # [1] "a b c d" "1 3 4 " "x y z"
An alternative way of writing the same pattern is x{2,}.
x{2,}
1.4m articles
1.4m replys
5 comments
57.0k users