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

Time:10-19

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.

CodePudding user response:

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;

CodePudding user response:

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');
  •  Tags:  
  • c#
  • Related