0

I need regex (named in code myRegex) which will match all functions (function1, function2, function3).

public static void main(String[] args) {

    String template = "f[0-9]"; // like f1, f2 etc
    String myRegex = "fun\\((" + template + "*)\\)"; //todo what regex?
    Pattern myPattern = Pattern.compile(myRegex);

    String function1 = "fun(f1)";
    String function2 = "fun(f1,f9)"; //myRegex don't match
    String function3 = "fun(f1,f9,f4)"; // myRegex don't match

    List<String> functions = Lists.asList(function1, function2, function3);
    for (String function : functions) {
        Matcher matcher = myPattern.matcher(function);
        while (matcher.find())
        {
            System.out.println(function + " match!");//works only for function1
        }
    }

}

Elements in brackets must be seperated by comma (,). It must work for other funcions with many arguments like :function4 = "fun(f1,f9,f4,f5,f7)";

3 Answers 3

2

Please use below.

String myRegex = "fun\\((" + template + ",)*" + template + "?\\)";

If you want to cater to fun() as well - without any parameters, use below

String myRegex = "fun\\((" + template + ",)*(" + template + ")?\\)";
Sign up to request clarification or add additional context in comments.

2 Comments

And if you need to also factor for fun(), then you can use the updated solution as well..
Note that the first regex also matches fun(f) while the second one also matches fun(f1,).
1

Use the following regex pattern:

fun\(f[0-9](?:,f[0-9]){0,2}\)

This will match any function named fun() having between 1 and 3 f arguments. Your actual Java regex pattern should be defined as:

Pattern myPattern = Pattern.compile("fun\\(f[0-9](?:,f[0-9]){0,2}\\)");

1 Comment

Thanks, sorry for editing my post after your answer. (Until my edit it was correct answer)
0

Regex

Use the following regex. It will also work if there are spaces between arguments or parentheses:

fun\s*\(\s*(?:f[0-9])?(?:\s*,\s*f[0-9])*\s*\)

Demo

https://regex101.com/r/hndzov/1

Java string

Pattern myPattern = Pattern.compile("fun\\s*\\(\\s*(?:f[0-9])?(?:\\s*,\\s*f[0-9])*\\s*\\)")

Explanation


Regex Description
fun Match exactly the characters fun
\s Match any whitespace character
\s* Match 0 or more whitespaces
\(, \( Match opening and closing parentheses
f Match character f
[0-9] Match any digit from 0-9
(?:) Make a group but don't capture it

Cons

Also matches a parameter list with a leading comma like fun(,f2, f3).

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.