RegExp matching string doesn't start with mine

For PMD, I would like to have a rule that warns me of these ugly variables that start with mine. This means that I must accept all variables that DO NOT start with mine.

So, I need RegEx (re), which behaves as follows:

re.match('myVar') == false re.match('manager') == true re.match('thisIsMyVar') == true re.match('myOtherVar') == false re.match('stuff') == true 

I tried different ones (I list them here later, sorry, now they do not have access), but it does not work yet.

+44
regex regex-negation pmd
Jan 22 '10 at 9:44
source share
4 answers

You can either use the lookahead statement as others have suggested. Or, if you just want to use the basic regular expression syntax:

 ^(.?$|[^m].+|m[^y].*) 

This matches strings of 0 or 1 character length ( ^.?$ ) And therefore cannot be my . Or strings with two or more characters, where, when the first character is not m , the following characters may follow ( ^[^m].+ ); or if the first character is m , then a y ( ^m[^y] ) does not follow.

+30
Jan 22 '10 at 10:09
source share
 ^(?!my)\w+$ 

must work.

It first ensures that it is not possible to match my at the beginning of a line, and then matches alphanumeric characters to the end of the line. Spaces anywhere on the line will throw a regex error. Depending on your input, you may need to either draw spaces in the front and back of the line before passing it to the regular expression, or use additional options for spaces in the regular expression, for example ^\s*(?!my)(\w+)\s*$ . In this case, backreference 1 will contain the name of the variable.

And if you need to make sure that the variable name starts with a specific group of characters, say [A-Za-z_] , use

 ^(?!my)[A-Za-z_]\w*$ 

Note the change from + to * .

+99
Jan 22 '10 at 9:48 on
source share
 /^(?!my).*/ 

(?!expression) - negative result; it corresponds to a position in which expression does not match the beginning at that position.

+34
Jan 22
source share

Wouldn't it be more clear to read a positive match and reject these lines - instead of matching a negative one to find the lines to accept?

 /^my/ 
+5
Sep 12 2018-11-12T00:
source share



All Articles