Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex replace all newline characters with comma

Tags:

regex

With regex, how do I replace each newline char (\n) with a comma (,)?

Like this:

Demetrius Navarro Tony Plana Samuel L. Jackson 

To:

Demetrius Navarro,Tony Plana,Samuel L. Jackson 

Not in a particular programming lang, just standard regex. Something like this:

(.*) $1 //This just takes the whole string and outputs it as is, I think 
like image 528
userBG Avatar asked Jan 16 '12 19:01

userBG


People also ask

How do you replace a line with a comma in notepad?

Notepad++: Remove new line and add comma Then do this: CTRL + H to open the Replace window. Then select Regular Expression in Search Mode. In the Find What, enter [\r\n]+. Then in the Replace with, enter the comma (,) and maybe followed by a space if you also want to add that.

What is the use of \n in regex?

"\n" matches a newline character.

How do I find and replace a new line in Notepad ++?

Open Notepad++ and the file you want to edit. In the file menu, click Search and then Replace. In the Replace box, in the Find what section, type ^\r\n (five characters: caret, backslash 'r', and backslash 'n'). Leave the Replace with section blank unless you want to replace a blank line with other text.


2 Answers

/\n/\,/ 

In Vim: :%s/\n/\,/g or with a space after the comma (as it is customary): :%s/\n/\,\ /g

Annoyin' 30 characters for an answer :)

like image 25
Rook Avatar answered Sep 17 '22 13:09

Rook


To match all newline characters, /\n/g. In order to replace them, you need to specify a language. For example, in JavaScript:

str.replace(/\n/g, ","); 

Live example

A simple Google search reveals how it's done in C#:

Regex.Replace(str, "\n", ","); 

After reading some of your comments, I searched how to do it in Perl. This should do it:

s/\n/,/g; 
like image 179
Alex Turpin Avatar answered Sep 19 '22 13:09

Alex Turpin