r - 在长于 n 个字符的单词之间包含一个空格
问题描述
我有一个字符向量。
x <- c('This is a simple text', 'this is a veryyyyyyyyyy long word', 'Replacethis andalsothis')
n
我想在比字符长的单词之间插入一个空格。对于这个例子,我们可以考虑n = 10
。我更喜欢一个regex
解决方案,但如果您认为还有其他选择,我不介意尝试。
我正在寻找的输出 -
c('This is a simple text', 'this is a veryyyyyyy yyy long word', 'Replacethi s andalsothi s')
我已经尝试通过对我的数据进行必要的更改来使用这篇文章中的解决方案,但它没有提供所需的输出。
sub('(.{10})(?=\\S)//g', '\\1 ', x, perl = TRUE)
#[1] "This is a simple text" "this is a veryyyyyyyy long word" "Replacethis andalsothis"
解决方案
您可以使用
gsub("\\b(\\w{10})\\B", "\\1 ", x) # If your words only consist of letters/digits/_
gsub("(?<!\\S)(\\S{10})(?=\\S)", "\\1 ", x, perl=TRUE) # If the "words" are non-whitespace char chunks
x <- c('This is a simple text', 'this is a veryyyyyyyyyy long word', 'Replacethis andalsothis')
gsub("\\b(\\w{10})\\B", "\\1 ", x)
# => [1] "This is a simple text" "this is a veryyyyyyy yyy long word" "Replacethi s andalsothi s"
x <- c("this is a veryyyyyyy|yyy long word")
gsub("(?<!\\S)(\\S{10})(?=\\S)", "\\1 ", x, perl=TRUE)
# => [1] "this is a veryyyyyyy |yyy long word"
正则表达式匹配...
\b
- 单词边界(\w{10})
- 十个字字符\B
- 仅当右侧立即出现另一个单词 char 时(因此,第十个单词 char 不是单词的结束字符)。
和
(?<!\S)
- 字符串开头或空格后的位置(\S{10})
- 第 1 组:十个非空白字符(?=\S)
- 紧靠右边,必须有一个非空白字符。
推荐阅读
- c# - 父控件绑定命令到 ContextMenu MenuItem
- c# - 如何以最佳方式在 Unity 中实例化 UI 图像的静态网格?
- r - 替换空(NA)数据框中的行而不将因子转换为整数
- node.js - Neo4jError:消息“提交”不能由处于就绪状态的会话处理
- android - 如何在 Android Studio 中解决这个问题
- c++ - 将二进制(exe、zip 等)文件读入 char*、c++
- javascript - 为什么这个 forEach 映射是未定义的?
- javascript - 使用ajax向laravel发送数据
- javascript - 从 JavaScript 发现本地网络服务器?
- bash - 按列和数值排序