You avoid //
-commented lines with:
^(?!\/\/).*
Explanation (also at regex101):
^
Start of a line
(?!\/\/)
Not a literal leading //
(this is a negative lookahead)
.*
Any number of any character (to skip blank lines, change to .+
)
If you're worried about leading white space, use ^(?!\s*\/\/).*
instead.
Now to get to the part about matching only line three.
If you want to match more than the absence of a comment, change the .*
to what you want to match. I'm not exactly sure what you want to match and not match, so this is a guess based on what intentions I can glean from your attempt.
^(?!\/\/).*\bMessagebox\((?!.*\bmb_taskmodal\b).*
This has the aforementioned exclusion for commented lines, then it matches Messagebox(
following a non-word character (or nothing) except if it is eventually followed by mb_taskmodal
as a full word, then anything else.
I'm using \b
a bit here. That just means exactly one side (either before or after the \b
) has a word character (a letter, number, or underscore) and the other side has a non-word character. The "b" stands for "[word] boundary". Escaped non-word characters are always literals, so \(
and \/
are a literal (
and /
respectively.
Note that this regex will still match Messagebox(a,b,c, mb_ok); // |mb_taskmodal);
. Resolving that is nontrivial since the inline comment indicator is two characters. I can answer that too, but hopefully you don't need it.
Solutions with grep:
$ grep -v '^//' FILENAME # discard comments
$ grep -v '^//' FILENAME |grep -vFw 'mb_taskmodal' # also discard mb_taskmodal
Grep's -v
flag inverts the match. -F
disables regexes and uses a plain text match (faster), and -w
requires word boundaries around the query (the same as \bmb_taskmodal\b
assuming GNU grep without -F
).
Extended Regular Expression (ERE) comment-filtering solution (no lookaround):
(If you're using grep, consider grep -v '^//' FILENAME
instead)
^(.?$|[^\/]{2}|[^\/]\/|\/[^\/]).*
Explanation (also at regex101):
^
Start of a line
(…)
Capture group (PCRE can inhibit capturing with (?:…)
instead) containing either
- Alternation one
.?
Any character, zero or one time (change to ..?
to skip blank lines)
$
End of line
- Alternation two
[^\/]{2}
Any character except a /
, twice
- Alternation three
[^\/]
Any character except a /
\/
A literal /
- Alternation four (order is swapped)
\/
A literal /
[^\/]
Any character except a /
.*
Any number of any character (including zero, required by alternation one)
This will match a blank line or a line like /
or j
or a longer non-comment line.