正则表达式:按名称,重量/计数和价格拆分字符串

时间:2017-09-19 05:26:41

标签: java regex string

所以我需要拆分字符串:

Laundry Detergent                2X Ultra Free Clear                                 50 oz          11.99

分为:

Laundry Detergent                2X Ultra Free Clear

50 oz

11.99

我到目前为止最好的是this。我知道它甚至不适用于此 字符串,但它确实需要分离一些其他字符串。这是我无法解决的问题之一。

一些示例字符串:

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

1 个答案:

答案 0 :(得分:1)

您可以尝试这种方法:(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