Search code examples
regexlookbehindnegative-lookbehind

RegExp match lines NOT starting with at-symbol


If I write this regexp (?<=^[\t ]*@).+ I can match only the lines starting with optional spaces (but not newlines) and at-symbol, without matching the at-symbol.

Example: @test Matches "test", but not the " @".

I'm trying to match lines that it first not space character is not the at-symbol. For that purpose I negate the look-behind, resulting in this: (?<!^[\t ]*@).+.

But it matches lines even if their first non-space character is the at-symbol.

I've tried regexps like these: ^[\t ]*[^@].*, (?<=^[\t ]*[^@]).+, (?<=^[\t ]*)(.(?!@)).*. All of then matches lines even their first non-space character is the at-symbol.

How can I do to match lines not starting with optional spaces (not newlines) and the at-symbol?

matches
    matches
m@tches
    m@tches
@Doesn't match
    @Doesn't match

Thanks!


Solution

  • Your pattern was good except two things:

    • you need a lookahead (followed with), not a lookbehind
    • you need to anchor your pattern at the start of the line

    So, if you read the text line by line:

    ^(?![ \t]*@).+
    

    If you read the whole text you need to use the multiline modifier to make ^ to match the start of the line (and not the start of the string by default):

    (?m)^(?![ \t]*@).+
    

    (or an other way to switch on this m modifier)