zach the mack zach the mack - 6 months ago 21
Java Question

scanner.useDelimiter() regex java

I have a string in an inconvenient format. Here is an example:

(Air Fresheners,17)->(Chocolate Chips,14)->(Juice-Frozen,24)


I need to go through this string and extract only the first items in the parenthesis. So using the snippet from above as input, I would like my code to return:

Air Fresheners
Chocolate Chips
Juice-Frozen


Note that some of the items have
-
in the name of the item. These should be kept and included in the final output. I was trying to use:

Scanner.useDelimiter(insert regex here)


...but I am not having any luck. Other methods of accomplishing the task are fine, but please keep it relatively simple.

Answer

Try this one

  • Use regex to split on the basis of )->(

    String s="(Air Fresheners,17)->(Chocolate Chips,14)->(Juice-Frozen,24)";
    
    Pattern regex = Pattern.compile("\\)->\\(");
    Matcher regexMatcher = regex.matcher(s);
    int i=0;
    while (regexMatcher.find()) {
        System.out.println(s.substring(i+1,regexMatcher.start()));
        i=regexMatcher.end()-1;
    }
    System.out.println(s.substring(i+1,s.length()-1));
    
  • Try String.split() method

    String s = "(Air Fresheners,17)->(Chocolate Chips,14)->(Juice-Frozen,24)";
    
    for (String str : s.substring(1, s.length() - 1).split("\\)->\\(")) {
        System.out.println(str);
    }