regex - 删除一定长度的单词之间的空格

标签 regex r string

我有以下种类的字符串:

A B C Company
XYZ Inc
S & K Co

我想删除这些字符串中仅在 1 个字母长度的单词之间的空格。例如,在第一个字符串中,我想删除 A 之间的空格。 BC但不在 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/

相关文章:

android - 在 EditText 中仅允许基于正则表达式的选定字符

regex - 如何正确转义 XSD 模式中的正则表达式模式?

r - 将列中的值转换为现有数据框中的行名称

java - 验证字符串(PPS 编号)

ruby - 如何拆分包含 Ruby 中的集合的字符串?

java - 使用匹配器/模式从 http 文档中提取字符串

R bootstrap 按组加权平均值与数据表

r - 如何将输入和输出沉入R中的文本文件中?

带有字符串的 Java 7 switch 语句不起作用

Python:使用正则表达式从字符串中提取数字