1

Want a regex for NUMERIC(p,s) NUMERIC will always be there and I just want to check whether inside brackets my values are comma separated or not. For example NUMERIC(10,20) so my regex would also contain "NUMERIC(" and comma checking for numbers and ")"

I have tried for comma check but not able to get the NUMERIC with "(" and ")" in my regex.

I have tried with "^NUMERIC\([0-9]+(,[0-9]+)*"

public static void main(String[] args) {
                String regex="^NUMERIC\\([0-9]+(,[0-9]+)*"
        String v="NUMERIC(1,2)";
        System.out.println(v.matches(regex));
    }

The expected result is the regex which would give me true for any comma separated number value within "NUMERIC(" and ")"

tushar_lokare
  • 461
  • 1
  • 8
  • 22
Shubham kapoor
  • 394
  • 3
  • 18
  • You're missing the literal closing parenthesis: `"^NUMERIC\\([0-9]+(, ?[0-9]+)?\\)"` – ernest_k Feb 11 '19 at 06:30
  • your regex is also taking 3 numeric value in brackets, for example NUMERIC(1,2,3) its also giving true for 3 numbers. I only want 2 numbers in brackets NUMERIC(20,5)-->> true NUMERIC(1,2,3)-->> false – Shubham kapoor Feb 11 '19 at 06:34
  • I didn't note that. I've changed it. (Use `(, ?[0-9]+)?` instead of `(, ?[0-9]+)*`) – ernest_k Feb 11 '19 at 06:35

2 Answers2

2

.matches() expects the entire string to match, and your regex doesn't contain a token for the closing parenthesis.

If there are always two values p and s, you should use something like

public static void main(String[] args) {
                String regex="NUMERIC\\([0-9]+,[0-9]+\\)"
        String v="NUMERIC(1,2)";
        System.out.println(v.matches(regex));
    }

If the second parameter is optional:

public static void main(String[] args) {
                String regex="NUMERIC\\([0-9]+(?:,[0-9]+)?\\)"
        String v="NUMERIC(1)";
        System.out.println(v.matches(regex));
    }

See also Difference between matches() and find() in Java Regex

Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
0

Use this regular exp.

^NUMERIC\([0-9]+(,[0-9]\){1})

I just modified yours.

TAB
  • 1,944
  • 8
  • 28
  • 45