Regex to match blank line and comments in a file

erb, regex, ruby

Solution

Match Comments and End-of-Line

/
  ^      # match start of line
  \s*    # match zero or more spaces
  (\#|$) # match comment symbol or end-of-line
/x

Compressed, the regex looks like this:

/^\s*(#|$)/

Prose Explanation

The `\s*` means that any amount of whitespace immediately after the start of line, including none at all, can match. `(\#|$)` uses alternation, so either of the patterns within the parentheses can match. NB: The backslash is only needed to escape the comment symbol when using the `x` option, which ignores whitespace and comments in the regular expression; if you aren't using `x` then leave the backslash out.

The pattern will therefore match start-of-line followed by optional whitespace, which must then be immediately followed by either a comment symbol or an end-of-line. Because the match is anchored, it will not match strings like `"foo # bar"` or `" Array#string\n"` because they won't match the required pattern.

Problem

How do I ignore comments or blank/empty lines in a file when reading? I thought `/^[\s#]*$/` would do the job but it didn't: ``` irb(main):180:0> open(inFile, 'r').each { |ln| puts ln if ln !~ /^[\s#]*$/ } .... .... # and ..... ThIs Is A cOmMeNt ..... .... .... => #<File:/tmp/running-instances.txt> irb(main):181:0> ``` What am I missing here? Any help would be highly appreciated. Cheers!! PS. I can do the separately in two steps though: ``` open(inFile, 'r').each { |ln| next if ln =~ /^\s*$/; puts ln if ln !~ /#[^#]*$/ } ```

Original source