Henry
Henry

Reputation: 31

Regex: Split string by name, weight/count, and price

So I need to split the string:

Laundry Detergent                2X Ultra Free Clear                                 50 oz          11.99

Into:

Laundry Detergent                2X Ultra Free Clear

50 oz

11.99

The best I have so far is this. I understand it doesn't even work with this string but it does some of the other strings I need to separate. This is one of the strings I can't work out.

Some example strings:

Ravioli                          Beef                                                15 oz          1
Pear Halves                      100% Juice                                          15 oz          1.3
Gatorade                         Sports Drink                                        8/20 oz        5.48

Upvotes: 1

Views: 270

Answers (1)

Mustofa Rizwan
Mustofa Rizwan

Reputation: 10476

You may try this approach: ( run here )

final String regex = "^((?:\\S+\\s?)+)\\s{2,}((?:\\S+\\s?)+)\\s{2,}((?:\\S+\\s?)+)\\s{2,}(\\d+(\\.\\d+)?)$";
    final String string = "Laundry Detergent         2X Ultra Free Clear              50 oz          11.99\n"
         + "Ravioli                   Beef                             15 oz          1\n"
         + "Pear Halves               100% Juice                       15 oz          1.3\n"
         + "Gatorade                  Sports Drink                     8/20 oz        5.48";

    final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
    final Matcher matcher = pattern.matcher(string);

    int cnt=1;
    while (matcher.find()) {
            System.out.println("###### result #######"+cnt++);
            System.out.println("Group " + 1 + ": " + matcher.group(1));
            System.out.println("Group " + 2 + ": " + matcher.group(2));
            System.out.println("Group " + 3 + ": " + matcher.group(3));
            System.out.println("Group " + 4 + ": " + matcher.group(4));
        }

Output:
###### result #######1
Group 1: Laundry Detergent 
Group 2: 2X Ultra Free Clear 
Group 3: 50 oz 
Group 4: 11.99
###### result #######2
Group 1: Ravioli 
Group 2: Beef 
Group 3: 15 oz 
Group 4: 1
###### result #######3
Group 1: Pear Halves 
Group 2: 100% Juice 
Group 3: 15 oz 
Group 4: 1.3
###### result #######4
Group 1: Gatorade 
Group 2: Sports Drink 
Group 3: 8/20 oz 
Group 4: 5.48

Upvotes: 1

Related Questions