1

I'm trying to extract Dockerfile ARG values which are usually of these forms:

$foo, expected output: foo
${foo}, expected output: foo

I want to capture the string after $. I'm trying this regex right now but it doesn't seem to working for second test case with curly braces:

private static String extract(String input) {
    Pattern argPattern = Pattern.compile("^\\$([^{}]+)$");
    Matcher matcher = argPattern.matcher(input);
    if (matcher.find()) {
        return (matcher.group(1));
    }
    return null;
}

Could anyone please tell me what I'm missing here?

3
  • What kind of chars can there be in between { and }? Only letters, digits, _ or more? Commented Sep 28, 2020 at 19:59
  • I think docker allows letters, digits and _ Commented Sep 28, 2020 at 20:03
  • Ok, then [^{}] in my solution below can be replaced with another \w. Commented Sep 28, 2020 at 20:06

1 Answer 1

1

You can use

\$(?:\{([^{}]+)\}|(\w+))

See the regex demo. Details:

  • \$ - a $ char
  • (?:\{([^{}]+)\}|(\w+)) - either of the two alternatives:
    • \{([^{}]+)\} - {, then Group 1 capturing one or more chars other than { and } and then a }
    • | - or
    • (\w+) - Group 2: any one or more letters, digits or underscores.

See a Java demo:

String s = "$foo1 expected output: foo ${foo2}, expected output: foo2";
Pattern pattern = Pattern.compile("\\$(?:\\{([^{}]+)\\}|(\\w+))");
Matcher matcher = pattern.matcher(s);
while (matcher.find()){
    if (matcher.group(1) != null) {
        System.out.println(matcher.group(1)); 
    } else { 
        System.out.println(matcher.group(2)); 
    }
}

Output: foo1 and foo2.

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

1 Comment

Thanks a lot for your response!

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.