I am doing something which seems very simple to me, yet the regex is not behaving as I had thought it would. The file I am parsing is a fstab, I am trying to ignore commented lines (begin with "#.") I also want to ignore any 'comment' lines which are preceded by whitespace. My example file
and code# This file is a comment and should not be used # This comment has one leading space # This comment has three leading spaces /dev/mapper/centos-var_log /var/log xfs defaults + 1 2 /dev/donstest /expert none 1 1 -rw,noglob # this is a fs #/dev/donstest22 /expert none 1 1 -rw,noglob # this is a + fS
#!/usr/bin/perl use strict; open (MYFILE, "./file.txt" ) or die "Could not open file: $! \n"; while ( my $line = <MYFILE> ) { chomp $line; if ( $line =~ /^\s*[^#].*/ ) { print "NOT Comment: $line \n"; } else { print "IS Comment: $line \n"; } }
My output:
IS Comment: # This file is a comment and should not be used NOT Comment: # This comment has one leading space NOT Comment: # This comment has three leading spaces NOT Comment: /dev/mapper/centos-var_log /var/log xfs + defaults 1 2 NOT Comment: /dev/donstest /expert none 1 1 -rw,noglob + # this is a fs NOT Comment: #/dev/donstest22 /expert none 1 1 -rw,noglo +b # this is a fS
What am I missing? As I understand /^\s*^#/ to mean "match any strings which may have zero of more whitespace characters from line begining followed by any character not a '#' the \s* should be greedy up to the first non-whitespace character. If I replace my regex with /^\s*^#\s ... it works as desired.
In reply to regex whitespace quantifers by halak77
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |