繁体   English   中英

Java 正则表达式字符串模式匹配

[英]Java Regex String pattern matching

我需要找到以下字符串的模式匹配:

HI {{contact::first_name=testok}} and Tag value {{contact::last_name=okie}}

所以模式匹配器应该返回以下两个字符串作为结果:

{{contact::first_name=testok}}
{{contact::last_name=okie}} 

我已经写了正则表达式模式,因为=之后它可以包含任何字符,所以我添加了.*

\{\{(contact|custom)::[_a-zA-Z0-9]+=?.*\}\}

但是上面的正则表达式模式是这样返回的

{{contact::first_name=testok}} and Tag value {{contact::last_name=okie}}

实现这一目标的任何解决方案。

试试这个模式(\\{\\{.*?\\}\\})

这里演示

通过在不情愿的量词旁边指定方括号(将尽可能多地抓住,直到第一次出现右方括号),您可以完全简化您的模式以获取双大括号(包括方括号)之间的任何内容。

String input = "HI {{contact::first_name=testok}} and Tag value {{contact::last_name=okie}}";
//                           | escaped curly bracket * 2
//                           |     | reluctant quantifier for any character 1+ occurrence
//                           |     |  | closing curlies
//                           |     |  | 
Pattern p = Pattern.compile("\\{\\{.+?\\}\\}");
Matcher m = p.matcher(input);
while (m.find()) {
    System.out.printf("Found: %s%n", m.group());
}

输出

Found: {{contact::first_name=testok}}
Found: {{contact::last_name=okie}}

您可以使用以下内容:

Pattern p = Pattern.compile("\\{\\{(.*?)\\}\\}");
Matcher m = p.matcher("HI {{contact::first_name=testok}} and Tag value {{contact::last_name=okie}}");

while (m.find()) {
    System.out.println(m.group());
}

可以在此处找到正则表达式的说明。

您可以使用递归模式: {{.*?(\\1)*.*?}}

解释:

.*? - 捕获任何字符的零次或多次出现(非贪婪)

(\\1)* - 再次匹配整个模式(零次或多次)

演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM