-4

I want to split the string first with "duration=" and the remaining part of the string, with the code below Im able to do that. Now I want to check if the second part of the string is containing any comma(,) and split that values accordingly

        String data = "duration=WEEKLY,MONTHLY";
        pattern = Pattern.compile("duration=(\\S*),(\\S*)", Pattern.CASE_INSENSITIVE);
        matcher = pattern.matcher(data);
        if (matcher.find()) {

            System.out.println(matcher.group(2)); //this prints MONTHLY(as it is group(2))
  }

I want to print "WEEKLY,MONTHLY". How can I get the entire string?

matcher.toMatchResult() or matcher.toString() returns the object instance.

Any help would be highly appreciated. Thanks

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
user2340345
  • 793
  • 4
  • 16
  • 38
  • `String.split` is enough. First split on `=` then split on `,` the second cell (if any). A regex to get an unknown amount of values is complicated. You can use the regex to get the "value" part, then split it if you want – AxelH Nov 29 '17 at 07:37
  • `System.out.println(matcher.group(1));` – Wiktor Stribiżew Nov 29 '17 at 07:38
  • `"duration=WEEKLY,MONTHLY".split("duration=")[1].split(",");` – jrook Nov 29 '17 at 07:39

1 Answers1

1

A regex like this will not work properly if you have only one value or more than two. The regex will not match with "duration=MONTHLY".

But you can use it to get the "value" part then simply String.split to get the result

    String data = "duration=WEEKLY,MONTHLY";
    pattern = Pattern.compile("duration=(.*)", Pattern.CASE_INSENSITIVE);
    matcher = pattern.matcher(data);
    if (matcher.find()) {
        String value = matcher.group(1); //get the values
        String[] values = value.split(","); //split on the comma
        for(String s : values){ //iterate the values
            System.out.println(s);
        }
    }
AxelH
  • 14,325
  • 2
  • 25
  • 55