userBG
userBG

Reputation: 7170

Regex replace all newline characters with comma

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

Upvotes: 35

Views: 125545

Answers (2)

Rook
Rook

Reputation: 62528

/\n/\,/

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

Upvotes: 4

Alex Turpin
Alex Turpin

Reputation: 47776

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;

Upvotes: 42

Related Questions