THX
THX

Reputation: 573

regex: match on negating a set of abitrary whitespaces before and after a 'comment' character

I am looking for a regex to (non)match a comment character wrapped by arbitrary whitespaces

For example with '#' as comment character:

lines supposed to be match:

 code line here
   code line here

lines supposed to be not matched:

 #code line here
 # code line here
   #   code line here

So, something like a negation of the set (zero/*whitespaces # zero/*whitespaces)

 ^(\s#\s)

Upvotes: 0

Views: 73

Answers (3)

The fourth bird
The fourth bird

Reputation: 163287

For your example data, if lookahead is supported you could use a negative lookahead to assert that from the start of the string what is on the right is not 0+ times a whitespace char followed by a #.

If that is the case, then match the whole string.

^(?!\s*#).+$

That will match:

  • ^ Start of the string
  • (?! Negative lookahead
    • \s*# Match 0+ times a whitespace char, then #
  • ) Close lookahead
  • .+ Match any char except newline 1+ times
  • $ End of the string

regex101 demo

Upvotes: 1

0xAA55
0xAA55

Reputation: 55

The following regex will match lines that don't have the character "#"

^((?!^\s+#).)*$

Upvotes: 2

AlexL
AlexL

Reputation: 355

May be something not optimized, but try this:

^[^#]*(?!\s*#).

This will get all symbols from the beginning of the line that are not followed by spaces + # combination.

Upvotes: 1

Related Questions