我有以下种类的字符串:
A B C Company
XYZ Inc
S & K Co
我想删除这些字符串中仅在 1 个字母长度的单词之间的空格。例如,在第一个字符串中,我想删除
A
之间的空格。 B
和 C
但不在 C
之间和公司。结果应该是:ABC Company
XYZ Inc
S&K Co
在
gsub
中使用的正确正则表达式是什么?为了这?
最佳答案
这是您可以执行此操作的一种方法,看看如何&
混入而不是一个单词字符...
x <- c('A B C Company', 'XYZ Inc', 'S & K Co', 'A B C D E F G Company')
gsub('(?<!\\S\\S)\\s+(?=\\S(?!\\S))', '', x, perl=TRUE)
# [1] "ABC Company" "XYZ Inc" "S&K Co" "ABCDEFG Company"
解释:
首先,我们断言两个非空白字符不前后接。然后我们查找并匹配空格“一次或多次”。接下来,我们先行断言后面跟着一个非空白字符,同时断言下一个字符不是非空白字符。
(?<! # look behind to see if there is not:
\S # non-whitespace (all but \n, \r, \t, \f, and " ")
\S # non-whitespace (all but \n, \r, \t, \f, and " ")
) # end of look-behind
\s+ # whitespace (\n, \r, \t, \f, and " ") (1 or more times)
(?= # look ahead to see if there is:
\S # non-whitespace (all but \n, \r, \t, \f, and " ")
(?! # look ahead to see if there is not:
\S # non-whitespace (all but \n, \r, \t, \f, and " ")
) # end of look-ahead
) # end of look-ahead
关于regex - 删除一定长度的单词之间的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26538292/