0

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"

2
  • I understand it so that the CRLF must only be removed if the string starts and ends with CRLF. If only one instance must be removed, you may use Regex.Replace(s, @"\A\r\n(.*)\r\n\z", RegexOptions.Singleline). A non-regex way is still preferred: if (s.EndsWith("\r\n") && s.StartsWith("\r\n")) s = s.Substring(1, s.Length-2) Commented Dec 7, 2016 at 21:54
  • @KGreve I revisited your question to see if I got chosen for the answer. I see you have added two more strings as examples that weren't there when I answered. I checked both of the new strings and they still have the \r\n removed with my answer. Is there some issue you're having with the answer? Commented Dec 7, 2016 at 22:21

3 Answers 3

1
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

Sign up to request clarification or add additional context in comments.

Comments

1
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"

2 Comments

This works if you only use one \\ not with both str = Regex.Replace(str, @"^(\r\n)+|(\r\n)+$", "");
@KGreve Oh good catch! I didn't actually try it out in C#, just an online regex tester, sorry about that. I edited the answer, which apparently removes it as marked as "correct".
0

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))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.