Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex that matches a newline (\n) in C#

Tags:

c#

.net

regex

OK, this one is driving me nuts.... I have a string that is formed thus:

var newContent = string.Format("({0})\n{1}", stripped_content, reply) 

newContent will display like:
(old text)
new text

I need a regular expression that strips away the text between parentheses with the parenthesis included AND the newline character.

The best I can come up with is:

const string  regex = @"^(\(.*\)\s)?(?<capture>.*)"; var match= Regex.Match(original_content, regex); var stripped_content = match.Groups["capture"].Value; 

This works, but I want specifically to match the newline (\n), not any whitespace (\s) Replacing \s with \n \\n or \\\n does NOT work.

Please help me hold on to my sanity!

EDIT: an example:

public string Reply(string old,string neww)         {             const string  regex = @"^(\(.*\)\s)?(?<capture>.*)";             var match= Regex.Match(old, regex);             var stripped_content = match.Groups["capture"].Value;             var result= string.Format("({0})\n{1}", stripped_content, neww);             return result;         }  Reply("(messageOne)\nmessageTwo","messageThree") returns : (messageTwo) messageThree 
like image 631
Dabblernl Avatar asked Jul 23 '09 23:07

Dabblernl


People also ask

What is the regex for newline?

"\n" matches a newline character.

How do you match a character including newline in regex?

By default in most regex engines, . doesn't match newline characters, so the matching stops at the end of each logical line. If you want . to match really everything, including newlines, you need to enable "dot-matches-all" mode in your regex engine of choice (for example, add re. DOTALL flag in Python, or /s in PCRE.

What does \+ mean in regex?

Example: "a\+" matches "a+" and not a series of one or "a"s. ^ the caret is the anchor for the start of the string, or the negation symbol. Example: "^a" matches "a" at the start of the string. Example: "[^0-9]" matches any non digit.

What is multiline in regex?

Multiline option, or the m inline option, enables the regular expression engine to handle an input string that consists of multiple lines. It changes the interpretation of the ^ and $ language elements so that they match the beginning and end of a line, instead of the beginning and end of the input string.


2 Answers

If you specify RegexOptions.Multiline then you can use ^ and $ to match the start and end of a line, respectively.

If you don't wish to use this option, remember that a new line may be any one of the following: \n, \r, \r\n, so instead of looking only for \n, you should perhaps use something like: [\n\r]+, or more exactly: (\n|\r|\r\n).

like image 139
Jon Grant Avatar answered Sep 30 '22 09:09

Jon Grant


Actually it works but with opposite option i.e.

 RegexOptions.Singleline 
like image 21
Saulius Avatar answered Sep 30 '22 07:09

Saulius