每隔 >n 个字符替换子字符串(有条件地为空格插入换行符)

Replace substring every >n characters (conditionally insert linebreaks for spaces)

我想用 R 中一个相当长的字符向量中的换行符 (\n) 替换 spaces。但是,我不想替换 every space,但前提是子字符串超过一定数量的字符 (n)。

示例:

mystring <- "this string is annoyingly long and therefore I would like to insert linebreaks" 

现在我想在每个 space 的 mystring 中插入换行符,条件是每个子字符串的长度大于 20 个字符 (nchar > 20)。

因此,生成的字符串应该如下所示:

"this string is annoyingly\nlong and therefore I would\nlike to insert linebreaks") 

在第 25、26 和 25 个字符后插入换行符 (\n)。

我怎样才能做到这一点? 也许结合了 gsubstrsplit?

您可以使用 .{21,}?\s 正则表达式匹配任何 21 个(自 nchar > 20 起)字符或更多,但尽可能少,直到最接近的空格:

> gsub("(.{21,}?)\s", "\1\n", mystring)
[1] "this string is annoyingly\nlong and therefore I would\nlike to insert linebreaks"

详情:

  • (.{21,}?) - 第 1 组捕获任意 21 个字符或更多,但尽可能少(因为 {21,}?lazy 量词)
  • \s - 一个空格

替换包含对第 1 组的反向引用以在空格和换行符之前重新插入文本(如果需要,也可以随意添加 CR)。