Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to match begin or end of a line using C#'s Regex?

Tags:

c#

.net

regex

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?

like image 916
MaikoID Avatar asked Jul 06 '11 12:07

MaikoID


2 Answers

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.

like image 160
Qtax Avatar answered Nov 01 '22 09:11

Qtax


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

like image 15
Kirill Polishchuk Avatar answered Nov 01 '22 11:11

Kirill Polishchuk