2

I would like to write a regular expression to extract parameter1 and parameter2 of func1(parameter1, parameter2), the length of parameter1 and parameter2 ranges from 1 to 64.

(func1) (\() (.{1,64}) (,\\s*) (.{1,64}) (\))

My version can not deal with the following case (nested function)

func2(func1(ef5b, 7dbdd))

I always get a "7dbdd)" for parameter2. How could I solve this?

5 Answers 5

3

Use "anything but closing parenthesis" ([^)]) instead of simply "anything" (.):

(func1) (\() (.{1,64}) (,\s*) ([^)]{1,64}) (\))

Demo: https://regex101.com/r/sP6eS1/1

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

Comments

1

Use [^)]{1,64} (match all except )) instead of .{1,64} (match any) to stop right before the first )

(func1) (\() (.{1,64}) (,\\s*) (.{1,64}) (\))
                                ^
                                replace . with [^)]

Example:

// remove whitespace and escape backslash!
String regex = "(func1)(\\()(.{1,64})(,\\s*)([^)]{1,64})(\\))";
String input = "func2(func1(ef5b, 7dbdd))";
Pattern p = Pattern.compile(regex); // java.util.regex.Pattern
Matcher m = p.matcher(input); // java.util.regex.Matcher
if(m.find()) { // use while loop for multiple occurrences
    String param1 = m.group(3);
    String param2 = m.group(5);

    // process the result...
}

If you want to ignore whitespace tokens, use this one:

func1\s*\(\s*([^\s]{1,64})\s*,\s*([^\s\)]{1,64})\s*\)"

Example:

// escape backslash!
String regex = "func1\\s*\\(\\s*([^\\s]{1,64})\\s*,\\s*([^\\s\\)]{1,64})\\s*\\)";
String input = "func2(func1 ( ef5b, 7dbdd ))";
Pattern p = Pattern.compile(regex); // java.util.regex.Pattern
Matcher m = p.matcher(input); // java.util.regex.Matcher
if(m.find()) { // use while loop for multiple occurrences
    String param1 = m.group(1);
    String param2 = m.group(2);

    // process the result...
}

Comments

0

Hope this helpful

func1[^\(]*\(\s*([^,]{1,64}),\s*([^\)]{1,64})\s*\)

Comments

0
(func1) (\() (.{1,64}) (,\\s*) ([^)]{1,64}) (\))

Comments

0
^.*(func1)(\()(.{1,64})(,\s*)(.{1,64}[A-Za-z\d])(\))+

Working example: here

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.