使用gsub删除多个空格和尾部空格 [英] Removing multiple spaces and trailing spaces using gsub
问题描述
如何仅用1个gsub删除多个空格和尾随空格?我已经将此函数设置为trim <- function(x) gsub(' {2,}',' ',gsub('^ *| *$','',x))
,但是我正试图仅用1个gsub重写它.
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.
实际上,我想根据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 ''
推荐答案
使用正向后方查找当前空间是否以空格开头:
Use a positive lookbehind to see if the current space is preceded by a space:
^ *|(?<= ) | *$
在此处查看操作: http://regex101.com/r/bJ1mU0
这篇关于使用gsub删除多个空格和尾部空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!