John P. S.
John P. S.

Reputation: 383

How can I remove line break tags from a character vector with Regular Expressions

How can I remove the \n line break tag from a string using regular expressions?

I tried using stringr::str_replace(), but failed.

For example, I have the string:

  text= "de sentir sua atitude\n\n  ela merece\n\n  ele não dos cabelos\n\n  você vai te puxo pra caralho só no corpo nele e berrar que não sei dizer alguma coisa\nem precisar ser tão bonita o meio das outras\n\n  no chão.\nespecialmente quando ele levou tanto buscava. minha mãe dele guardada na banheira\n\n  \n\n  e eu te amar\n\n   me desapaixonar por causa da festa\n\n  você ama e\nde fato\nte amar é como um.\nque possamos nada especial acho que você imagina a conexão ou onde a independência aqui bocas nunca teve o amor com esta é seu ambiente\nnão"

And I tried using [:punct:]n, and \\n{1,}, but all of them failed in doing so when I ran than into the replacement function with:

stringr::str_replace(text, '([:punct:]n|\\n{1,})', ' ')

Upvotes: 1

Views: 309

Answers (2)

J_Alaniz
J_Alaniz

Reputation: 98

Using R base

string <- "aaaa\naaaaaaa\naaaaa\n"
gsub('\n', '', string)

will output "aaaaaaaaaaaaaaaa"

Also works with your text. Sometimes the simplest is the best solution, no need for regex, it is technically a literal match.

Upvotes: 1

akrun
akrun

Reputation: 887148

We can use str_remove_all which would make it compact instead of using the replacement argument in str_replace_all with ""

stringr::str_remove_all(text, '([[:punct:]]|\\n{1,})')

NOTE: str_replace replaces only the first instance and not more than one

Upvotes: 1

Related Questions