.NET Framework Bookmark and Share   
 index > Regular Expressions > Multiline Option does not work
 

Multiline Option does not work

Hi,

Below is the sample piece of code(The code is in VB.NET), where I am expecting an answer of "true"with my basic knowledge of Regular Expressions.
---------------------------------------------------
'VB

Dim r As New Regex("^def$", RegexOptions.Multiline)

Dim d As String =String.Format("{0}{1}{2}{3}{4}{5}", "abc", System.Environment.NewLine, "def", System.Environment.NewLine, "def", System.Environment.NewLine)

MsgBox(r.Match(d).Success)
-----------------------------------------------------------
The answer I get is false, but there are two "def" in 2nd and 3rd line of the data and Multiline option is enabled, I have checked it with VS 2005 and VS 2008, both give me answer as false. What is the mistake I have done? Please help.

Thanks and Best Regards,
Bennz


Benz
Bennz
Actually, it does work, but not as one would expect. According to the MSDN documentation on "$"...
>>>"$" The match must occur at the end of the string or before \n at the end of the line or string.<<<

The confusion comes because we in MS land expect \r\n to be treated as a new line. \r is carriage-return, and \n is a new-line. So, try this example...

            string pattern = @"^def\r$";
            string test = @"abcdefgh
def
def
";
            if (Regex.IsMatch(test, pattern, RegexOptions.Multiline))
                    Console.WriteLine("{0}", test);
            foreach (Match mx in Regex.Matches(test, pattern, RegexOptions.Multiline))
                Console.WriteLine("{0} matches", mx.Value);



See if this helps.

Les Potter, Xalnix Corporation, Yet Another C# Blog
xalnix
Hi Xalnix

Thanks a lot for your answer.

It worksby adding"\r" in the string.

I think it wouldbe helpful for all a MS fans, if they add this as a note in the MSDN documentation.

Thanks and Best Regards,
Bennz
  • Edited byBennz Monday, September 14, 2009 8:12 AMThe reply was not outputted properly
  •  
Bennz

You can use google to search for other answers

Custom Search

More Threads

• Url Rewriting - Trouble with optional query string parameters
• Regex Question
• URL Regex
• Email address with a name
• Regex to Substring without cutting off word
• Regex to grab servername
• RTF, extract a tag
• RegEx that Includes "Word A" but does not contain "Word B"
• How to ask .net to return the minimal match?
• ISO/ANSI C++ question. keyword:delete