RegExp matching string not starting with my
^(?!my)\w+$
should work.
It first ensures that it's not possible to match my
at the start of the string, and then matches alphanumeric characters until the end of the string. Whitespace anywhere in the string will cause the regex to fail. Depending on your input you might want to either strip whitespace in the front and back of the string before passing it to the regex, or use add optional whitespace matchers to the regex like ^\s*(?!my)(\w+)\s*$
. In this case, backreference 1 will contain the name of the variable.
And if you need to ensure that your variable name starts with a certain group of characters, say [A-Za-z_]
, use
^(?!my)[A-Za-z_]\w*$
Note the change from +
to *
.
/^(?!my).*/
(?!expression)
is a negative lookahead; it matches a position where expression
doesn't match starting at that position.
You could either use a lookahead assertion like others have suggested. Or, if you just want to use basic regular expression syntax:
^(.?$|[^m].+|m[^y].*)
This matches strings that are either zero or one characters long (^.?$
) and thus can not be my
. Or strings with two or more characters where when the first character is not an m
any more characters may follow (^[^m].+
); or if the first character is a m
it must not be followed by a y
(^m[^y]
).
Wouldn't it be significantly more readable to do a positive match and reject those strings - rather than match the negative to find strings to accept?
/^my/