如何区分两个正则表达式,一个是另一个的子串?

时间:2017-06-08 02:51:43

标签: java regex

我有两种类型的模式,如下所示:

  • 第一类:${<varName>}
  • 类型II:$${<varName>}

可以单独找到模式,或者在字符串中包含多个匹配。我需要找到这些模式的出现,所以我通过匹配正则表达式编写了一个搜索查询。然而,问题在于对于任何类型II模式,它们本身包含类型I模式的匹配。例如,$${newVar}将被检测为$${newVar}${newVar}两次。我只希望前者被退回。我使用的正则表达式是:

  • 第一类:\$\{[a-zA-Z0-9]+\}
  • 类型II:\$\$\{[a-zA-Z0-9]+\}

您可以看到检测到的字符串here(下方)

的示例

enter image description here

请注意,第二次检测是正确的,而第一次检测是不需要的。

是否还有修改这些正则表达式以满足我的需要?还是有其他选择吗?请随时提出建议。欢迎所有答案!!谢谢大家。

2 个答案:

答案 0 :(得分:2)

您似乎需要找到两种类型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

答案 1 :(得分:0)

对于${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}

在这里演示:

Rextester