16

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?

peirix
  • 36,512
  • 23
  • 96
  • 126

2 Answers2

24

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.

Scott Coldwell
  • 868
  • 7
  • 14
Blixt
  • 49,547
  • 13
  • 120
  • 153
  • excellent informative answer. thanks! (: I was just doing a regex search in Eclipse, so consuming characters doesn't matter. (btw, Velocimacro is sorta like a function in Velocity (open source templating language), and you call them like normal functions, only every command in Velocity starts with the hash key) – peirix Aug 12 '09 at 10:00
  • Thanks, how can I say "Don't match #, including if followed by any number of spaces?" – Dominic May 06 '16 at 09:18
13
/([^#]|^)addButton/

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

Adam Byrtek
  • 12,011
  • 2
  • 32
  • 32
  • Or to make it a little more robust (so that it will match at the beginning of a string), `/(?:^|[^#])addButton/` – Amber Aug 12 '09 at 06:50
  • awesome! ... I think I should invest some time in regex...it just keeps popping up everywhere... – peirix Aug 12 '09 at 06:51