Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The way to strip newline characters

Let's say we have a long string with multiple newline characters:

char const* some_text = "part1\n\npart2\npart3";

Now the task is to replace all '\n' characters with spaces if it appears only once between text parts, and at the same time leave all '\n' characters if it appears more than once. In other words:

"123\n456" => "123 456"
"123\n\n456" => "123\n\n456"
"123\n\n456\n789" => "123\n\n456 789"

What is the best way to do this?


1 Answers

The following regular expression detects single occurrences of newlines:

([^\n]|^)\n([^\n]|$)

|-------|
no newline before
(either other character or beginning of string)

        |--|
       newline

           |--------|
        no newline after
   (either other character or end of string)

You can use that regular expression in std::regex_replace in order to replace those single newlines by spaces (and keeping the matched character before and after the newline by adding $1 and $2):

std::string testString("\n123\n\n456\n789");
std::regex e("([^\n]|^)\n([^\n]|$)");
std::cout << std::regex_replace(testString, e, "$1 $2") << std::endl;
like image 83
mastov Avatar answered Feb 02 '26 16:02

mastov