Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex: Finding strings that doesn't start with X

Tags:

regex

I am completely hopeless with regular expressions...

I have a Velocimacro named #addButton, and I have a JS function named addButton(). Now I want to find all the places the JS function is called. So I need to search for "addButton", where "addButton" doesn't start with the hash key.

Any ideas?

like image 834
peirix Avatar asked Aug 12 '09 06:08

peirix


People also ask

How do you search for a RegEx pattern at the beginning 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.

What does \+ mean in RegEx?

For examples, \+ matches "+" ; \[ matches "[" ; and \. matches "." . Regex also recognizes common escape sequences such as \n for newline, \t for tab, \r for carriage-return, \nnn for a up to 3-digit octal number, \xhh for a two-digit hex code, \uhhhh for a 4-digit Unicode, \uhhhhhhhh for a 8-digit Unicode.

What is difference [] and () in RegEx?

[] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9.

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

I don't know what Velocimacro is (judging from the other answer I guess "addButton" will appear on its own line?), but the sure-fire way of finding the word "addButton" that is not preceeded by # is the following:

/(?<!#)\baddButton\b/

It will:

  1. (?<!#) (?)
    • Make sure that the current position is not preceeded by a # (hash mark)
  2. \b (?)
    • Make sure that the current position is a word boundary (in this case it makes sure that the previous character is not a word character and that the next character is)
  3. addButton (?)
    • Match "addButton"
  4. \b (?)
    • Make sure that there is a word boundary at the current position. This avoids matching things like "addButtonNew" (because there is no word boundary between "addButton" and "New")

A difference with this regular expression and the other is that this one will not consume the character before "addButton".

A good resource for learning about regular expressions is regular-expressions.info. Click the (?) link in the list above for a link to the relevant page for that part of the regex.

like image 111
Blixt Avatar answered Oct 15 '22 14:10

Blixt


/([^#]|^)addButton/

It will match every string where "addButton" is not preceded by "#" or the beginning of the string.

like image 37
Adam Byrtek Avatar answered Oct 15 '22 16:10

Adam Byrtek