tags:

views:

407

answers:

4

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

+1  A: 

If you're trying to match line endings then you may find

Regex.Match("string", "regex", RegexOptions.Multiline)

helps

spender
sorry, that doesn't work
Dabblernl
+3  A: 

You are probably going to have a \r before your \n. Try replacing the \s with (\r\n).

JP Alioto
+3  A: 

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

Jon Grant
Don't forget that alternation isn't greedy; if you apply your regex to `"\r\n"` it will only match `"\r"`. I would use `(\n|\r\n?)` or maybe `(\r\n?|\n)` instead.
Alan Moore
I could not get it to work with the Multiline option.(\n|\r|\r\n) did the trick. It surfaced that in this particular case \r\n was necessary to get a match, even though I inserted only \n in the string to be matched.
Dabblernl
+2  A: 

A must have application when working with c# regex's and best of all it's free:

http://sourceforge.net/projects/regulator/

There's also:

http://www.ultrapico.com/Expresso.htm

see_sharp_guy