Java正则表达式匹配Dockerfile参数值

huangapple go评论75阅读模式
英文:

Java Regex to match Dockerfile arg values

问题

我正在尝试提取Dockerfile ARG值,这些值通常有以下形式:

$foo,预期输出:foo
${foo},预期输出:foo

我想捕获$后面的字符串。我目前正在尝试以下正则表达式,但似乎对于带有花括号的第二个测试用例不起作用:

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

请问有谁可以告诉我在这里漏掉了什么?

英文:

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?

答案1

得分: 1

你可以使用以下正则表达式:

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

详情:

  • \$ - 匹配 $ 字符
  • (?:\{([^{}]+)\}|(\w+)) - 两个可能的选择之一:
    • \{([^{}]+)\} - 匹配 {,然后捕获组 1 匹配除了 {} 之外的一个或多个字符,最后匹配 }
    • | - 或者
    • (\w+) - 捕获组 2:匹配一个或多个字母、数字或下划线字符

Java 演示 中的应用:

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)); 
    }
}

输出:foo1foo2

英文:

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.

huangapple
  • 本文由 发表于 2020年9月29日 03:56:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/64108802.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定