我有两种模式,如下所示:
${<varName>}$${<varName>}可以单独找到模式,或者在一个字符串中包含多个匹配。我需要找到这些模式的出现,所以我编写了一个查询,通过匹配regex进行搜索。但是,问题在于,对于任何类型II模式,它们本身都包含与第一类模式匹配的内容。例如,$${newVar}将被检测为$${newVar}和${newVar}的两倍。我只想把前者还回去。我使用的正则表达式是:
\$\{[a-zA-Z0-9]+\}\$\$\{[a-zA-Z0-9]+\}您可以看到检测到的字符串这里的示例(如下)

注意,第二次检测是正确的,而第一次检测是不需要的。
是否也有修改这些正则表达式以满足我的需要?或者有没有其他的选择?请随便建议。欢迎所有答案!!谢谢你们所有人。
发布于 2017-06-08 03:32:37
似乎您需要找到类型I和类型II模式的出现,所以您应该在一次扫描中做到这一点。
可以这样做:
String input = "adklsfjb$${xxx}dklsjfnsdklj${yyy}";
Pattern p = Pattern.compile("(\\$)?\\$\\{([^}]+)}");
for (Matcher m = p.matcher(input); m.find(); ) {
if (m.start(1) == -1) {
System.out.println("Found Type I match for variable '" + m.group(2) + "'" +
" at index " + m.start() + "-" + m.end());
} else {
System.out.println("Found Type II match for variable '" + m.group(2) + "'" +
" at index " + m.start() + "-" + m.end());
}
}输出
Found Type II match for variable 'xxx' at index 8-15
Found Type I match for variable 'yyy' at index 27-33更新
如果要用值替换模式,可以使用appendReplacement()和appendTail()。
示例:
String input = "adklsfjb$${xxx}dklsjfnsdklj${yyy}adljfhjh";
Map<String, String> type1 = new HashMap<>();
type1.put("xxx", "[type I with x's]");
type1.put("yyy", "[type I with y's]");
Map<String, String> type2 = new HashMap<>();
type2.put("xxx", "{TYPE 2 WITH x's}");
type2.put("yyy", "{TYPE 2 WITH y's}");
StringBuffer buf = new StringBuffer();
Matcher m = Pattern.compile("(\\$)?\\$\\{([^}]+)}").matcher(input);
while (m.find()) {
String var = m.group(2);
String repl = (m.start(1) == -1 ? type1.get(var) : type2.get(var));
if (repl != null)
m.appendReplacement(buf, Matcher.quoteReplacement(repl));
}
String output = m.appendTail(buf).toString();
System.out.println(output);输出
adklsfjb{TYPE 2 WITH x's}dklsjfnsdklj[type I with y's]adljfhjh发布于 2017-06-08 03:09:43
对于${varname}类型的变量,可以使用以下模式:
(^|[^$])\$\{.*?\}对于$${varname}类型的变量,您可以使用您已经想到的内容:
\$\$\{.*?\\}示例代码:
String input = "${beef} is a great thing to $${eat}. It has many ${health} benefits ";
input + "and is low in fat ${too}";
// single dollar sign variables
System.out.println("single dollar sign variables:");
String pattern = "(?:^|[^$])(\\$\\{.*?\\})";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(input);
while (m.find()) {
System.out.println("Found value: " + m.group(1));
}
// two dollar sign variables
System.out.println("two dollar sign variables:");
pattern = "(\\$\\$\\{.*?\\})";
r = Pattern.compile(pattern);
m = r.matcher(input);
while (m.find()) {
System.out.println("Found value: " + m.group(1));
}输出:
single dollar sign variables:
Found value: ${beef}
Found value: ${health}
Found value: ${too}
two dollar sign variables:
Found value: $${eat}演示这里:
雷克斯试验器
https://stackoverflow.com/questions/44425864
复制相似问题