0

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.

1
  • 1
    Please mention the tool/lang you're using. Commented Jun 8, 2022 at 9:48

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

I am looking for something more generic sadly, it could be something like Foo(out int n)
...then you asked the wrong question. Update your question with the generic problem. Most likely, you will need to write/use a parser here; regex alone won't help.
yeah it's difficult to explain specific use case, as I am trying to parse any C# function basically... either function call or function definition, just trying to extract everything that is separated by commas inside (,,,,)
another example would be public void Function(something here)
0

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.

Comments

0

Try this one

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.