Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression to replace "\r\n" only if not preceded by "." in a string

Tags:

regex

c#-4.0

Could you please provide a regular expression that I can use to replace all \r\n in a string, only when \r\n is not preceded by .?

like image 941
user1869870 Avatar asked Jan 15 '23 07:01

user1869870


1 Answers

To match a character, you can place the character inside brackets such as [.]. To not match it, you can start the character list with a caret such as [^.]. This will effectively match any character that is not a ..

For your specific case, you want to match \r\n that doesn't have a . in front of it. Combined with the above, you can use:

[^.]\r\n

To replace it, you'll want to "capture" the character that is not-a-period to keep it in the replacement. You can capture it by wrapping it in parentheses, such as ([^.]).

Using Regex.Replace(), it would be something like:

yourString = Regex.Replace(yourString, @"([^.])\r\n", "$1");

The $1 is the character matched and is re-replaced back into the string, now stripped of the \r\n.

like image 69
newfurniturey Avatar answered May 18 '23 21:05

newfurniturey