zach the mack zach the mack - 2 years ago 135
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

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 Source

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()) {
  • 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("\\)->\\(")) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download