Home > database >  Regex: how to extract function parameters
Regex: how to extract function parameters

Time:06-09

I could not find similar question with what I am trying to get at.

I have a function:

Foo(int n, str b, Bar1(), Bar2(smth));

I am trying to write regex to get the following matches:

int n
str b
Bar()
Bar2(smth) // don't need recursion

I've managed to do it in 2 separate regexes:

(?<=\().*(?=\))

to get:

int n, str b, Bar1(), Bar2(smth)

then on that string, I 've used:

[^,\s*][a-zA-Z\s<>.()0-9]*

to get:

int n
str b
Bar()
Bar2(smth)

But I would really like to do it in a single regex statement, is it possible to somehow capture first regex in a group and then run second regex on that group in a single statement? I am still quite vague on using groups.

CodePudding user response:

For the function call you happened to post, the following regex seems to work:

(?:\w  \w |\w \(\w*\))

This pattern matches, alternatively, a type followed by variable name, or a function name, with optional parameters. Here is a working demo.

CodePudding user response:

You can use

(?:\G(?!^)\s*,\s*|\()\K\w (?:\s \w |\s*\([^()]*\))

See the regex demo. Details:

  • (?:\G(?!^)\s*,\s*|\() - either the end of the preceding match and then a comma enclosed with zero or more whitespaces, or a ( char
  • \K - omit the text matched so far
  • \w - one or more word chars
  • (?:\s \w |\s*\([^()]*\)) - a non-capturing group matching one of two alternatives
    • \s \w - one or more whitespaces and then one or more word chars
    • | - or
    • \s* - zero or more whitespaces
    • \([^()]*\) - a ( char, then zero or more chars other than ( and ) and then a ) char.

CodePudding user response:

Try this one

((?<=\(|,\s)((\w \s) \w )|(\w \((\w (\,\s){0,1})*\)))

Check demo https://regex101.com/r/Bv1Y5L/1

  • Related