KGreve
KGreve

Reputation: 31

Using Regex to replace special character

I'm trying to get some code in c# to check the start or end of a string and see if it has "\r\n" in one of these locations and if it does I want these characters removed. I do not want to remove these characters if they are not at the start or end though.

ex:

string tempStringA = "\r\n123\r\n456\r\n";
string tempStringB = "\r\n123\r\n456";
string tempStringC = "123\r\n456\r\n";

tempStringA, tempStringB, and tempStringC would all become "123\r\n456"

Upvotes: 0

Views: 69

Answers (3)

Blake Thingstad
Blake Thingstad

Reputation: 1659

string str = @"\r\n123\r\n456\r\n";
str = Regex.Replace(str, @"^(\r\n)+|(\r\n)+$", "");

This works for your example and also works for "\r\n\r\n123\r\n456\r\n\r\n" if there are ever times where there is more than one of those characters.

Edit: Also works for "\r\n123\r\n456" and "123\r\n456\r\n"

Upvotes: 1

garyh
garyh

Reputation: 2852

var str1 = "\r\n123\r\n456\r\n";
var str2 = Regex.Replace(str1, @"^\r\n|\r\n$", "");

This just removes the \r\n at the start and end of the string

Upvotes: 1

Josiah
Josiah

Reputation: 504

This is not regex, but regex might be overkill here.

string.Join( "\r\n", "\r\n123\r\n456\r\n".Split(new string[]{"\r\n"}, StringSplitOptions.RemoveEmptyEntries))

Upvotes: 0

Related Questions