简体   繁体   中英

Java Regex String pattern matching

I need to find the pattern matching for the below string:

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

So the pattern matcher should return below two strings as the result:

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

I have written regex pattern as this, since after = it can contain any characters so i added .*

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

but the above regex pattern is returning like this

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

Any solution to achieve this.

try this pattern (\\{\\{.*?\\}\\})

here Demo

You can utterly simplify your pattern to get whatever's in between double curly brackets (brackets included), by specifying the brackets alongside a reluctant quantifier (will grab as much as possible until the first occurrence of the closing brackets).

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());
}

Output

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

You can use the following :

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());
}

Explanation of the regex can be found here .

You could use recursive pattern: {{.*?(\\1)*.*?}}

Explanation:

.*? - capture zero or more occurences of any character (non-greedy)

(\\1)* - match again whole pattern (zero or more times)

Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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