开发者

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

开发者 https://www.devze.com 2023-03-18 04:10 出处:网络
I\'m trying to match this expression: ^COMA1TA2000,.*$ with this text: # Qualquer linha iniciada por # será ignorada

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-20开发者_运维百科00,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?


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.


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


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.
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消