Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
如何仅使用 1 gsub 删除多个空格和尾随空格?我已经制作了这个功能trim <- function(x) gsub(' {2,}',' ',gsub('^ *| *$','',x)),但我试图只用 1 gsub 重写它。
trim <- function(x) gsub(' {2,}',' ',gsub('^ *| *$','',x))
实际上,我想精益如何根据 gsub 之后/之前的内容来匹配某些内容。在此示例中,我需要匹配前面有一个空格的所有空格,并将它们替换为 ''
使用正向lookbehind 来查看当前空格前面是否有空格:
^ *|(?<= ) | *$
在此处查看实际操作:http ://regex101.com/r/bJ1mU0