Search code examples
javascriptregexvisual-studio-coderegex-groupregex-greedy

RegEx for matching a word after specific word in multiple lines


There is regex feature to find words instead of "Ctrl + F" in some editor like VS Code, I'm trying to find a word after a specific word with some another lines.

For example, how to use regex to filter those "someFunction" with the specific "message" property as below:

...
someFunction({
  a: true,
  b: false
})
someFunction({
  a: true,
  b: false,
  c: false,
  d: true,
  message: 'I wnat to find the funciton with this property'
})
someFunction({
  a: true
})
...

The regex I tried is like:

/someFunction[.*\s*]*message/

But it did't work

How can I achieve this aim?


Solution

  • Your expression is just fine, you might want to slightly modify it as:

     someFunction[\S\s*]*message
    

    If you wish to also get the property, this expression might work:

    (someFunction[\S\s*]*message)(.*)
    

    You can add additional boundaries, if you like, maybe using regex101.com.

    enter image description here

    Graph

    This graph shows how your expression would work and you can visualize other expressions in jex.im:

    enter image description here

    Performance Test

    This script returns the runtime of a string against the expression.

    repeat = 1000000;
    start = Date.now();
    
    for (var i = repeat; i >= 0; i--) {
    	var string = "some other text someFunction \n            \n message: 'I wnat to find the funciton with this property'";
    	var regex = /(.*)(someFunction[\S\s*]*message)(.*)/g;
    	var match = string.replace(regex, "$3");
    }
    
    end = Date.now() - start;
    console.log("YAAAY! \"" + match + "\" is a match 💚💚💚 ");
    console.log(end / 1000 + " is the runtime of " + repeat + " times benchmark test. 😳 ");

    const regex = /(someFunction[\S\s*]*message)(.*)/;
    const str = `...
    someFunction({
      a: true,
      b: false
    })
    someFunction({
      a: true,
      b: false,
      c: false,
      d: true,
      message: 'I wnat to find the funciton with this property'
    })
    someFunction({
      a: true
    })
    ...`;
    let m;
    
    if ((m = regex.exec(str)) !== null) {
        // The result can be accessed through the `m`-variable.
        m.forEach((match, groupIndex) => {
            console.log(`Found match, group ${groupIndex}: ${match}`);
        });
    }