Java 中的模式匹配问题



我在正则表达式方面很差。我用谷歌搜索并对其有了基本的了解。

我有以下要求: 我的命令可能包含一些带有"$(VAR_NAME)"模式的字符串。我需要找出它是否有这种类型的字符串。如果是这样,我必须解决这些问题(我知道我应该怎么做,如果有这样的字符串)。 但是,问题是,如何查找命令是否具有"$(VAR_NAME)"模式的字符串。我的命令中可能有多个或零个这样的字符串模式。

据我所知,我写了下面的代码。如果我在下面的代码中使用,'pattern1',它是匹配的。但是,不是'pattern'有人可以帮忙吗?

提前谢谢你。

final String command = "somescript.file $(ABC_PATH1) $(ENV_PATH2) <may be other args too here>";
final String pattern = "\Q$(\w+)\E";
//final String pattern1 = "\Q$(ABC_PATH1)\E";
final Pattern pr = Pattern.compile(pattern);
final Matcher match = pr.matcher(command);
if (match.find())
{
System.out.println("Found value: " + match.group(0));
}
else
{
System.out.println("NO MATCH");
}

使用 \Q 和 \E 意味着您无法为变量名称设置捕获组,因为圆括号将按字面解释。

我可能会这样做,只是转义外部 $,( 和 )。

另外,如果您需要多个匹配项,则需要多次调用find(),我为此使用了while循环。

final String command = "somescript.file $(ABC_PATH1) $(ENV_PATH2) <may be other args too here>";
final String pattern = "\$\((\w+)\)";
final Pattern pr = Pattern.compile(pattern);
final Matcher match = pr.matcher(command);
while (match.find()) {
System.out.println("Found value: " + match.group(1));
}

输出

Found value: ABC_PATH1
Found value: ENV_PATH2

您可以使用Pattern.quote("Q$(w+)E")方法添加要传入编译方法的模式。

final Pattern pr = Pattern.compile(Pattern.quote("Q$(w+)E"));

模式可能如下所示:

public static void main(String[] args) {
final String command = "somescript.file $(ABC_PATH1) $(ENV_PATH2) <may be other args too here>";
final String pattern = "\$\((.*?)\)";
// final String pattern1 = "\Q$(ABC_PATH1)\E";
final Pattern pr = Pattern.compile(pattern);
final Matcher match = pr.matcher(command);
while (match.find()) {
System.out.println("Found value: " + match.group(1));
}
}

指纹:

Found value: ABC_PATH1
Found value: ENV_PATH2

问题是引号也适用于模式中的\w+,我认为这不是意图(因为它是,它匹配字符串"cmd $(\w+)",其中包括反斜杠,"w"和加号)。

该模式可以替换为:

final String pattern = "\$\(\w+\)";

或者,如果您仍想在第一部分使用 \Q 和 \E:

final String pattern = "\Q$(\E\w+\)";

我认为你把问题复杂化了。
由于$(是一个保留的"字",只需这样做来检查是否有出现:

command.indexOf("$(");

使用示例:

public class Test
{
private static final String[] WORDS;
static {
WORDS = new String[] {
"WORD1",
"WORD2"
};
}
public static void main(final String[] args) {
String command = "somescript.file $(ABC_PATH1) $(ENV_PATH2)";
int index = 0;
int i = 0;
while (true) {
index = command.indexOf("$(", index);
if (index < 0) {
break;
}
command = command.replace(command.substring(index, command.indexOf(")", index) + 1), WORDS[i++]);
}
}
}

它打印:somescript.file WORD1 WORD2

坚持原始来源:

public class Test
{
public static void main(final String[] args) {
final String command = "somescript.file $(ABC_PATH1) $(ENV_PATH2)";
int index = 0;
int occurrences = 0;
while (true) {
index = command.indexOf("$(", index);
if (index < 0) {
break;
}
occurrences++;
System.out.println(command.substring(index, command.indexOf(")", index++) + 1));
}
if (occurrences < 1) {
System.out.println("No placeholders found");
}
}
}

最新更新