Geet San
Geet San

Reputation: 98

Regex Pattern required in java for matching string starts with '{{' and ends with "}}"

Hi, I need to create a regex pattern that will pick the matching string starts with '{{' and ends with "}}" from a given string.

The pattern I have created is working same with the strings starting with '{{{' and '{{', Similarly with ending with '}}}' and

'}}'

Output of above code:
matches = {{phone2}}
matches = {{phone3}}
matches = {{phone5}}


**Expected Output**:
matches = {{phone5}}

I need only Strings which follows two consecutive pattern of '{' and '}' not three.

Sharing the code below


    package com.test;

    import java.util.regex.Matcher;
    import java.util.regex.Pattern;

    public class RegexTest {

    public static void main(String[] args) {

        String text = "<test>{{#phone1}}<a href=\"tel:{{{phone2}}}\">{{{phone3}}}</a>{{/phone4}} {{phone5}}></test>";

        //String pattern = "\\{\\{\\s*?(\\w*?)\\s*?(?!.*\\}\\}\\}$)";
        String pattern = "\\{\\{\\s*?(\\w*?)\\s*?}}";
            Pattern placeholderPattern = Pattern.compile(pattern);
            Matcher placeholderMatcher = placeholderPattern.matcher(text);
            while (placeholderMatcher.find()) {
                System.out.println("matches = " + placeholderMatcher.group());
            }

        }
    }

Upvotes: 1

Views: 106

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627082

You may use

String pattern = "(?<!\\{)\\{{2}\\s*(\\w*)\\s*\\}{2}(?!\\})";

Or, if empty or blank {{...}} are not expected, use

String pattern = "(?<!\\{)\\{{2}\\s*(\\w+)\\s*\\}{2}(?!\\})";

See the regex demo.

Details

  • (?<!\{) - a negative lookbehind failing the match if there is a { char immediately to the left of the current location
  • \{{2} - {{ substring
  • \s* - 0+ whitespaces
  • (\w*) - Group 1: one or more word chars (1 or more if + quantifier is used)
  • \s* - 0+ whitespaces
  • \}{2} - }} string
  • (?!\}) - a negative lookahead that fails the match if there is a } char immediately to the right of the current location.

See the Java demo:

String text = "<test>{{#phone1}}<a href=\"tel:{{{phone2}}}\">{{{phone3}}}</a>{{/phone4}} {{phone5}}></test>";
String pattern = "(?<!\\{)\\{{2}\\s*(\\w*)\\s*\\}{2}(?!\\})";
Pattern placeholderPattern = Pattern.compile(pattern);
Matcher placeholderMatcher = placeholderPattern.matcher(text);
while (placeholderMatcher.find()) {
    System.out.println("Match: " + placeholderMatcher.group());
    System.out.println("Group 1: " + placeholderMatcher.group(1));
}

Output:

Match: {{phone5}}
Group 1: phone5

Upvotes: 1

Related Questions