Note that there are some explanatory texts on larger screens.

plurals
  1. POMatch only a newline character
    primarykey
    data
    text
    <p>I have a text file which has lines of data separated by newlines. What I'm trying to do is count the number of lines in the file, excluding the ones that are only a newline. </p> <p>I'm trying to use a regular expression to look at each line as it is read, and if it starts with a newline character not include it in my line count, but I can't seem to get it to work. I've searched all over the place for how to do this with no results.</p> <p>Here's the method I've written to try to do this:</p> <pre><code>public int LineCounter() { StreamReader myRead = new StreamReader(@"C:\TestFiles\test.txt"); int lineCount = 0; string line; while ((line = myRead.ReadLine()) != null) { string regexExpression = @"^\r?\n"; RegexOptions myOptions = RegexOptions.Multiline; Match stringMatch = Regex.Match(line, regexExpression, myOptions); if (stringMatch.Success) { } else { lineCount++; } } return lineCount; } </code></pre> <p>I've tried changing the RegexOptions between <code>Singleline</code> and<code>Multiline</code>, I've tried putting <code>"\r|\n|\r\n"</code> into my pattern match, and I've tried removing the <code>^</code> from the expression, but I can't seem to get it to work. No matter what I do, my <code>lineCount</code> always ends up being the total number of lines in the file, including the newlines.</p> <p>I'm apparently overlooking something obvious, but I'm not yet familiar enough with the C# language to see what's wrong. Everything looks like it should work to me. Can someone please help me out?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload