2

I've been looking for "get everything but" regex questions, but I couldn't make it work for my case. I was trying to get everything except a closing comment */.

I have this expression that gets the me declaration of javascript functions:

/(\b(f|F)unction(.*?)\((.*?)\)\s*\{)/g

The only problem I found with it at the moment is that it also gets me things such as:

function to do whatever */ function demo (el, hop) {

Instead of

function demo (el, hop) {

When having this function declaration with a comment containing the word function.

/** * recursive function to do whatever */ function demo (el, hop) { /*whatever*/ }

This is what I tried so far with no result:

/(\b(f|F)unction^((?!\*\/).)*?\((.*?)\)\s*\{)/g

Which is basically using what recommending in this post:

^((?!hede).)*$  //recommended
^((?!\*\/).)*?  //mine

What am I doing wrong?

Community
  • 1
  • 1
Alvaro
  • 40,778
  • 30
  • 164
  • 336
  • "Which is basically using what recommending in this post:": I suggest you to read the other answers, in particular the benchmark and ridgerunner answer, because you have choosen the slowest way. – Casimir et Hippolyte May 21 '15 at 12:11

2 Answers2

1

You can use this negative lookahead based regex:

/(\bfunction((?!function).)*\((.*?)\)\s*{)/gi

RegEx Demo

(?!function) is a negative lookahead that will match next character only if there is no function keyword. Check my demo for your examples.

anubhava
  • 761,203
  • 64
  • 569
  • 643
0

This approach will find most function declarations, including those for anonymous functions.

/\s?function(\s+\w+)?\s*\([^\)]*\)/i

Nice tool for testing regexes: https://regex101.com/

user2182349
  • 9,569
  • 3
  • 29
  • 41
  • 1
    Doesn't seem to get all: https://regex101.com/r/nS6bO7/1 in comparison with https://regex101.com/r/nS6bO7/2 – Alvaro May 21 '15 at 11:19