Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
236 views
in Technique[技术] by (71.8m points)

r - How to match the starting and ending character for str_replace_all

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?

question from:https://stackoverflow.com/questions/65903769/how-to-match-the-starting-and-ending-character-for-str-replace-all

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use the pattern xx+ (“at least two repetitions of “x”) and replace that with a space:

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,}.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...