Search code examples
regexregex-lookaroundsregex-group

Regex, negative lookahead for a part of expression


i'm evaluating an expression using regex patterns. In an expression, I have words. I want to forbid some reserved words like true and false (but i want to accept words like obstruent)

So I define, for example, this pattern for a word:

(?!^true$)(?!^false$)[^ =]{1,50}

Ok, this works fine for a single word, but it doesn't to evaluate an expression. Let us assume that an expression is always an assignment, this pattern

((?!^true$)(?!^false$)[^ =]{1,50})=((?!^true$)(?!^false$)[^ =]{1,50})

doesn't work. In fact it match true=false

What can I do to avoid this problem? Thanks


Solution

  • In a general case, you need to use custom boundaries here, since your words are chunks of characters other than whitespace and =:

    (?<![^\s=])(?!(?:true|false)(?![^=\s]))[^\s=]{1,50}(?![^=\s])
    

    See the regex demo.

    Details

    • (?<![^\s=]) - a location in the string that is not immediately preceded with a char other than whitespace and =
    • (?!(?:true|false)(?![^=\s])) - immediately to the right, there should be no true and false that are followed with a =, whitespace or end of string
    • [^\s=]{1,50} - one ot fifty chars other than whitespace and =
    • (?![^=\s]) - immediately to the right, there should be no character other than = or whitespace.

    To validate the assignment, you may use

    ^(?!(?:true|false)=)[^\s=]{1,50}=(?!(?:true|false)$)[^\s=]{1,50}$
    

    See the regex demo

    Here, at the start, the true or false are curbed with = on the right and then, on the right, with a $ (end of string).