Removing multiple spaces and trailing spaces using gsub

我只是一个虾纸丫 提交于 2019-11-29 14:49:37

问题


How can I remove multiple spaces and trailing spaces using only 1 gsub? I already made this function trim <- function(x) gsub(' {2,}',' ',gsub('^ *| *$','',x)), but i'm trying to rewrite it with only 1 gsub.

Actually, I want lean how to match something based in what is after/before it with gsub. In this example I need to match all spaces that are preceeded by a single space, and replace them by ''


回答1:


Use a positive lookbehind to see if the current space is preceded by a space:

^ *|(?<= ) | *$

See it here in action: http://regex101.com/r/bJ1mU0



来源:https://stackoverflow.com/questions/14737266/removing-multiple-spaces-and-trailing-spaces-using-gsub

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