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

前端 未结 3 1785
耶瑟儿~
耶瑟儿~ 2020-12-16 12:23

I\'m trying to match this expression:

^COMA1TA2000,.*$

with this text:

# Qualquer linha iniciada por # será ignorada
# Cara         


        
相关标签:
3条回答
  • 2020-12-16 12:36

    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 讨论(0)
  • 2020-12-16 12:44

    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.

    0 讨论(0)
  • 2020-12-16 12:56

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

    0 讨论(0)
提交回复
热议问题