0

I want to validate the string {233}{232}{112}{3232} with regex in java. I am using Pattern.compile("\\{([^\\}]*.?)\\}") but I'm not able to validate this string.

Here in the string, multiple ids are divided by the curly braces and the ID must be numeric.

Some test cases:

Test case 1: {122}{323} //true

Test case 2: {122}323} //false

Test case 3: {122323} //true

Test case 4: {122},{323} //false

Test case 5: {xx}{YY} //false

Can anyone help me on this? Your help will be really appreciated.

1
  • 1
    Pattern.compile("(\\{([^{}]*.?)\\})*") perhaps? Commented Mar 26, 2018 at 5:51

1 Answer 1

2

Your pattern is off, you should be using this:

(?:\{\\d*\})+

You seem to have some confusion about how to tell the regex engine to capture everything up until the first closing bracket. One could use [^}]*, but one could have also used lazy dot .*?. Your code appears to be using both, sort of. In this case though, we can just state take any number of digits, because a digit is by definition not a closing brace.

Full code:

String input = "{233}{232}{112}{3232}";

if (input.matches("(?:\\{\\d*\\})+")) {
    System.out.println("Match!");
}

Demo

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

3 Comments

This does still pass the {xx}{YY} test that he stated should fail, it should also be checking that it is also a digit (?:\{[^}\D]*\})+
@PraveenRawat My name isn't Tin, but appreciate the feedback.
sorry @TimBiegeleisen for spell mistake

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.