25

I'm trying to match this expression:

^COMA1TA2000,.*$

with this text:

# Qualquer linha iniciada por # será ignorada
# Caracteres que não podem serem usados na nomenclatura das copiadoras ou modelos.
# & < > " '
COMA1TA2000,ta-2000,hd,COMB1
#COMA2TA2000,ta-2000,hd,COMB2
#COMA3TA2000,ta-2000,hd,COMB3

I can do that using Notepad++, but I can't with the C# Regex class.

content = sr.ReadToEnd();
string pattern =  "^COMA1TA2000,.*$";
if(Regex.IsMatch(content, pattern))
System.Windows.Forms.MessageBox.Show("Test");

What am I missing?

1
  • Just to be clear, your IsMatch line is returning false?
    – Phil Gan
    Jul 6, 2011 at 12:07

3 Answers 3

36

You can use RegexOptions.Multiline, like so:

Regex.IsMatch(content, pattern, RegexOptions.Multiline)

Docs: http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regexoptions.aspx

If RegexOptions.Multiline is not set, ^ and $ will match beginning and the end* of the string, not the line like intended.

1
  • Do not forget that Windows uses CRLF line endings, so you may need to use \r?$ instead of $ in patterns used with a RegexOptions.Multiline option. Here, it does not matter because .*$ matches all text up to the first newline, LF char. In case you want to check if the line ends with a, you will need to write a\r?$. Jul 28 at 10:06
15

Or set multiline option in regex (?m): (?m)^COMA1TA2000,.*$

1
  • 1
    In an environment where I only have access to .net regular expressions, not to the code that creates and runs them - I thought I was out of luck, as it seemed like setting the multiline option was necessary for what I was trying to do. That totally works! Learned something new and nifty. :)
    – neminem
    Jan 31, 2014 at 0:50
1

Use File.ReadLines instead of ReadToEnd method and apply regex on each line.

What you're doing now, is reading the entire text as a block of text and MultiLine option sometimes breaks things down (as there are different CRLF characters in different operating systems, and stuff like that).

My suggestion is this:

string[] lines = File.ReadAllLines("path to your text file");
Regex regex = new Regex("^pattern$");
foreach (string line in lines)
{
    Match match = regex.Match(line.Trim())
    if (match.Successful)
    {
         // have your match here.
    }
}
1
  • It's a nice idea I will remember that in my next project. But for this question the first answer is the correct.
    – MaikoID
    Jul 7, 2011 at 17:23

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.