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

时间:2016-12-12 13:52:26

标签: r regex gsub

我想在R中的一个很长的字符向量中用换行符(\n)替换空格。但是,我不想替换每个空间,但仅限于如果子串强制执行一定数量的字符(n)。

示例:

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

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

因此,结果字符串应该如下所示:

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

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

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

1 个答案:

答案 0 :(得分:11)

您可以使用.{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,}?懒惰量词)
  • \\s - 空白

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

相关问题