Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

newline replacement in string using regex

I'am using the following regex to remove newlines from a string:

$description =~ s/\r//;
$description =~ s/\n//;

but afterwards I am getting true for:

$description =~ m/\n/

It seems regex did not replace all newlines from the string, any help with this?

like image 376
webaloman Avatar asked Dec 12 '22 11:12

webaloman


2 Answers

If you're trying to remove single chars, use tr rather than s///.

$description =~ tr/\r\n//d;

This will remove all occurrences of either \r or \n regardless of their respective positions in the string.

like image 91
Mat Avatar answered Jan 01 '23 17:01

Mat


Your substitutions are not global substitutions - they replace only the first instance of the pattern in the string. To make a global substitution, add a g after the final slash, like so:

$description =~ s/\r//g;
$description =~ s/\n//g;

You can also combine the two substitutions into a single substitution using a character set:

$description =~ s/[\n\r]//g;
like image 41
Tom Avatar answered Jan 01 '23 19:01

Tom