英文:
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));
}
}
输出:foo1
和 foo2
。
英文:
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
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论