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

问题描述 投票:5回答:1

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

例:

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

现在我想在每个空格中插入qazxsw poo中的换行符,条件是每个子串的长度大于20个字符(qazxsw poi)。

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

mystring

在25,26和25个字符后插入了换行符(nchar > 20)。

我怎样才能做到这一点?也许结合"this string is annoyingly\nlong and therefore I would\nlike to insert linebreaks") \n的东西?

r regex gsub
1个回答
11
投票

您可以使用gsub正则表达式匹配任何21(自strsplit)字符或更多,但尽可能少,直到最近的空格:

.{21,}?\s

细节:

  • nchar > 20 - 第1组捕获任何21个或更多的字符,但尽可能少(因为> gsub("(.{21,}?)\\s", "\\1\n", mystring) [1] "this string is annoyingly\nlong and therefore I would\nlike to insert linebreaks" 是一个懒惰的量词)
  • (.{21,}?) - 一个空白

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

© www.soinside.com 2019 - 2024. All rights reserved.