Got more questions? Find advice on: ASP | SQL | XML | Windows
in Search
Welcome to RegexAdvice Sign in | Join | Help

Count non-blank lines in C#

Last post 04-04-2012, 6:30 AM by mroshaw. 2 replies.
Sort Posts: Previous Next
  •  04-03-2012, 7:48 AM 84877

    Count non-blank lines in C#

    Hi all!

    I'm trying, and failing, to count the number of non-blank lines in a string in C#. In addition to 'empty lines', I also want to count lines with only 'white space' (spaces, tabs) as blank and I'm not sure how to do that.

    The regex that I'm currently using doesn't do this:

    var re = new Regex(@"\r?\n", RegexOptions.Multiline);

    var count = re.Matches(inString).Count;

    Any thoughts on how I might achieve this requirement would be greatly appreciated.

    Regards,

    mroshaw 

  •  04-03-2012, 7:59 PM 84883 in reply to 84877

    Re: Count non-blank lines in C#

    I'm not clear if you want to match non-blank lines or blank lines (even those that contain only whitespace characters) - you r posting seems to be a little contradictory on this. However the pattern you posted would seem to point towards counting blank lines. On the other hand the title is clear about counting non -blank lines.

    What your current pattern will do is to simply match the line-feed characters at the end of a line - it says nothing about what else is (or isn't) on that line.

    If you are wanting to count non-blank lines, then these can be defined as a line that contains at least one non-whitespace character.Therefore you could use something like

    ^.*\S.*\r?$

    with the "multiline" option set as you have in your pattern.

    Alternatively, to count blank lines (allowing for spaces or tabs) then something like

    ^[ \t]*\r?$

    should do. (By the way the character set contains a space and the tab character - if you want other whitespace characters such as the vertical tab, then add those into the the set definition).

    Susan

  •  04-04-2012, 6:30 AM 84887 in reply to 84883

    Re: Count non-blank lines in C#

    Hi Susan and many, many thanks for the reply!

    I do indeed want to count non-blank lines. The way the site has word wrapped my post has probably lead to confusion:
    "I also want to count lines with only 'white space' (spaces, tabs) as blank"

    Your definition of "a line that contains at least one non-whitespace character" is absolutely spot on so your proposed solution will do the job perfectly.

    Once again, please accept my sincere thanks for taking the time to reply in such detail.

    Kind regards,

    mroshaw

View as RSS news feed in XML