vr552
vr552

Reputation: 301

How to trim charcters from beginning and end of string with regex?

I'm trying to remove \r\n and '\n' from text. The problem is that sometimes they are necessary. E.g.:

\r\n \nTitle\r\nText on the next row\r\n\r\nSignature\r\n

The ones between the text should be kept. Expected output:

Title\r\nText on the next row\r\n\r\nSignature

The '\r\n' and '\n' and ' ' from the start of the string are gone, as well as '\r\n' from the end of it. The rest are kept. I've tried various things similar to this

var reg = new Regex(@"(^(\r\n)+?)");

but can't get it to work properly.

Upvotes: 1

Views: 530

Answers (2)

Caius Jard
Caius Jard

Reputation: 74605

I'd just

yourString.Trim()

it..

Or some variation on the overload that takes the chars if you ever want other than whitespace(or if you specifically want just those whitespace):

yourString.Trim("\r \n".ToCharArray()); //maybe store this ToCharArray call elsewhere as a fixed set of delimiters 
yourString.Trim(new[]{'\r','\n',' '}); //consider store elsewhere
yourString.Trim('\r','\n',' '); 

If it really has to be regex, you can capture all the interesting part:

Regex.Match("^[\r\n ]*(?<x>.?*)[\r\n ]*$").Groups["x"].Value;

Upvotes: 2

Charlieface
Charlieface

Reputation: 71509

You can use string.Trim() with multiple characters

var text = "\r\n \nTitle\r\nText on the next row\r\n\r\nSignature\r\n";

text = text.Trim('\r', '\n');

Upvotes: 1

Related Questions