0

I'm trying to write a regex expression that will check that a string is in the formation of a Set of integers

ex: {1, 23, -501, 52, 2387329, 0}

So far I've got:

Pattern p = [({(([0-9]+,)*[0-9]+)})]

But it doesn't seem to be working... Can anyone help me out?

Thanks!

Simon O'Hanlon
  • 58,647
  • 14
  • 142
  • 184
  • You don't handle `-` sign?? Can you show some examples of strings that work and don't work? – Floris Mar 24 '13 at 03:33
  • One useful technique as you develop complex regular expressions is to build them up from named Strings. `String lbrace = "[{]";` and `String sInteger = "[+-]?\\d+";`. Then build up your pattern from these. Look at the mail pattern in the second edition of Mastering Regular Expressions. – Eric Jablow Mar 24 '13 at 03:44
  • I'm very new to regex and am not really sure what I'm doing here. Some examples that work would be: {1, 2, 3} {} {3} and those that don't work are: {1 2 3} {a, b, c} – user1217119 Mar 24 '13 at 03:53
  • Do you _want_ `{1 2 3}` and `{a, b, c}` to work? – Floris Mar 24 '13 at 03:57
  • No. They should be numbers separated by commas. I can always take the spaces out by formatting the string, so even the spaces aren't necessary – user1217119 Mar 24 '13 at 03:58

3 Answers3

1
Pattern.compile("\\{\\s*(?:\\d+(?:\\s*,\\s*\\d+\\s*)*)?\\}")

matches curly brackets surrounding zero or more comma-separated non-negative decimal integers.

\\s matches any space character. The (?:...) are just for grouping, and the stuff between the curly brackets is effectively (decimal digits followed by (any number of commas then decimal digits)) optionally.

I don't know what notation you're using for

[({(([0-9]+,)*[0-9]+)})]

but it will definitely not match the empty set and won't match anything with spaces after a comma.

Mike Samuel
  • 118,113
  • 30
  • 216
  • 245
0

try this regex

"\\{((-?\\d+), ?)*-?\\d+}"
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
0

Try this out.

        String data = "{1, 23, -501, 52, 2387329, 0}";
    Pattern pattern = Pattern.compile("\\{(\\s?-?\\d+?\\,?\\s?)+?\\}");

    Matcher matcher = pattern.matcher(data);
    while (matcher.find()) {
        // Indicates match is found. Do further processing
        System.out.println(matcher.group());
    }
Ankur Shanbhag
  • 7,746
  • 2
  • 28
  • 38