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

gos*_*osz 6 regex r gsub

我想\n在R中的一个非常长的字符向量中用换行符(\n )替换空格.但是,我不想替换每个空格,但仅当子字符串强制执行一定数量的字符(n)时.

例:

mystring <- "this string is annoyingly long and therefore I would like to insert linebreaks" 
Run Code Online (Sandbox Code Playgroud)

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

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

"this string is annoyingly\nlong and therefore I would\nlike to insert linebreaks") 
Run Code Online (Sandbox Code Playgroud)

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

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

Wik*_*żew 12

您可以使用.{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"
Run Code Online (Sandbox Code Playgroud)

细节:

  • (.{21,}?)- 第1组捕获任何21个或更多的字符,但尽可能少(因为{21,}?是一个懒惰的量词)
  • \\s - 一个空白

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