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

I would like to replace spaces with strings ( \n) in a rather long chracter vector in R. However, I do not want to replace every space, but only if the substring displays a certain number of characters ( n).

Example:

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

Now I want to insert lines in mystringin each space, provided that each substring has a length of more than 20 characters ( nchar > 20).

Therefore, the resulting string should look like this:

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

Line lines ( \n) were inserted after 25, 26, and 25 characters.

How can i achieve this? Maybe something combining gsuband strsplit?

+4
1

.{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, ).

+8

Source: https://habr.com/ru/post/1663515/


All Articles