Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for removing leading and trailing carriage returns and line feeds from a sentence

Tags:

string

regex

Also is it possible to combine this with removing periods from within the string? The sentence may have spaces which I'd like to keep.

like image 839
Rasputin Jones Avatar asked Mar 31 '10 05:03

Rasputin Jones


People also ask

What is regex for carriage return?

You can use special character sequences to put non-printable characters in your regular expression. Use \t to match a tab character (ASCII 0x09), \r for carriage return (0x0D) and \n for line feed (0x0A).

How do I remove a carriage return from a string?

You could remove all newlines with: s = s. replaceAll("\\n", ""); s = s. replaceAll("\\r", "");

How do I remove all line breaks from a string?

Use the String. replace() method to remove all line breaks from a string, e.g. str. replace(/[\r\n]/gm, ''); . The replace() method will remove all line breaks from the string by replacing them with an empty string.

How do I remove carriage returns in r?

You need to strip \r and \n to remove carriage returns and new lines.


2 Answers

Search for

^[\r\n]+|\.|[\r\n]+$

and replace with nothing.

The specific syntax will depend on the language you're using, e. g. in C#:

resultString = Regex.Replace(subjectString, @"^[\r\n]+|\.|[\r\n]+$", "");

in PHP:

$result = preg_replace('/^[\r\n]+|\.|[\r\n]+$/', '', $subject);

in JavaScript:

result = subject.replace(/^[\r\n]+|\.|[\r\n]+$/g, "");

etc...

like image 195
Tim Pietzcker Avatar answered Nov 23 '22 09:11

Tim Pietzcker


You can find:

^[\r\f]+|[\r\f]+$

and replace it with

''

For the periods you can find

\.

and replace it with

''

Some languages provide you with function what take a a group of regex and replacements and do the replacement in one call to the function. Like the PHP's preg_replace.

like image 30
codaddict Avatar answered Nov 23 '22 11:11

codaddict