1

I would like someone to help me to rectify my regular expression to split this string:

{constraint.null.invalid}{0,1,2}

Basically, I want anything inside { and }, so my output must be:

  • constraint.null.invalid
  • 0,1,2.

My regular expression, which I've tried closely is:

\{([\S]+)\}

But the value I get is:

constraint.null.invalid}{0,1,2

What am I missing?

Sample code:

public static void main(String[] args) {
    Pattern pattern = Pattern.compile("\\{([\\S]+)\\}", Pattern.MULTILINE);
    String test = "{constraint.null.invalid}{0,1,2}";
    Matcher matcher = pattern.matcher(test);
    while (matcher.find()) {
        System.out.println(matcher.group(1));
    }
}

Thanks


PS: The string can contain values bounded by 1 or more { and }.

0

2 Answers 2

4

The + quantifier is greedy. Use +? for the reluctant version.

See http://docs.oracle.com/javase/tutorial/essential/regex/quant.html for details.

Sign up to request clarification or add additional context in comments.

Comments

2

a little different approach, with this pattern "\{([^\{\}]*)\}"

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

public class ReTest {

    /**
     * @param args
     */
    public static void main(String[] args) {
        String s = "bla bla {constraint.null.invalid} bla bla bla {0,1,2} bla bla";
        Pattern p = Pattern.compile("\\{([^\\{\\}]*)\\}");

        Matcher m = p.matcher(s);

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.