Home > Back-end >  JavaScript Regex finding all substrings that matches with specific starting and ending pattern
JavaScript Regex finding all substrings that matches with specific starting and ending pattern

Time:02-23

I want a Javascript regex or with any possible solution, For a given string finds all the substrings that start with a particular string and end with a particular character. The returned set of subStrings can be an Array.

this string can also have nested within parenthesis.

var str = "myfunc(1,2) and myfunc(3,4) or (myfunc(5,6) and func(7,8))";

starting char = "myfunc" ending char = ")" . here ending character should be first matching closing paranthesis.

output: function with arguments.

[myfunc(1,2),
 myfunc(3,4),
 myfunc(5,6),
 func(7,8)]

I have tried with this. but, its returning null always.

var str = "myfunc(1,2) and myfunc(3,4) or (myfunc(5,6) and func(7,8))";

var re = /\myfunc.*?\)/ig
var match;
while ((match = re.exec(str)) != null){
  console.log(match);
}

Can you help here?

CodePudding user response:

I tested your regex and it seems to work fine:

let input = "myfunc(1,2) and myfunc(3,4) or (myfunc(5,6) and func(7,8))"

let pattern = /myfunc.*?\)/ig 
// there is no need to use \m since it does nothing, and NO you dont need it even if you use 'm' at the beginning.

console.log(input.match(pattern)) 
//[ "myfunc(1,2)", "myfunc(3,4)", "myfunc(5,6)" ]

If you use (?:my|)func\(. ?\) you will be able to catch 'func(7,8)' too.

(?:my|)

(    start of group
?:   non capturing group
my|  matches either 'my' or null, this will match either myfunc or func
)    end of group

Test the regex here: https://regex101.com/r/3ujbdA/1

  • Related