Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegExp matching string not starting with my

For PMD I'd like to have a rule which warns me of those ugly variables which start with my.
This means I have to accept all variables which do NOT start with my.

So, I need a 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've tried different ones but haven't got it working yet.

like image 401
Dominik Sandjaja Avatar asked Jan 22 '10 09:01

Dominik Sandjaja


People also ask

Does not start with regex JS?

To check if a string does not start with specific characters using a regular expression, use the test() function and negate it. Make sure your regular expression starts with ^ , which is a special character that represents the start of the string.

How do you match the start of a string?

The meta character “^” matches the beginning of a particular string i.e. it matches the first character of the string. For example, The expression “^\d” matches the string/line starting with a digit. The expression “^[a-z]” matches the string/line starting with a lower case alphabet.

How do you check if a regex matches a string?

Use the test() method to check if a regular expression matches an entire string, e.g. /^hello$/. test(str) . The caret ^ and dollar sign $ match the beginning and end of the string. The test method returns true if the regex matches the entire string, and false otherwise.

What does regex 0 * 1 * 0 * 1 * Mean?

Basically (0+1)* mathes any sequence of ones and zeroes. So, in your example (0+1)*1(0+1)* should match any sequence that has 1. It would not match 000 , but it would match 010 , 1 , 111 etc. (0+1) means 0 OR 1.


2 Answers

^(?!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 *.

like image 198
Tim Pietzcker Avatar answered Oct 07 '22 08:10

Tim Pietzcker


/^(?!my).*/ 

(?!expression) is a negative lookahead; it matches a position where expression doesn't match starting at that position.

like image 39
Amber Avatar answered Oct 07 '22 06:10

Amber