Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 927
Chris Kao Avatar asked Oct 30 '25 06:10

Chris Kao


2 Answers

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}`);
    });
}
like image 191
Emma Avatar answered Nov 01 '25 21:11

Emma


you could use regex for mutliple-line search in VScode.

If you have several someFunction in the file and you only want to find the ones that have message field but skip those the others without message field in it.

use the following

  • Use lazy qualifier +?, it matches the text block from the first occurrence someFunction to the first occurrence of message
  • Use [^)] to make sure there is no close bracket between the someFunction and message
  • use \n to match multiple lines
someFunction([^)]|\n)+?message:

enter image description here

enter image description here

like image 41
Hui Zheng Avatar answered Nov 01 '25 21:11

Hui Zheng