首页 > 解决方案 > Java parse string using regex into variables

问题描述

I need to extract variables from a string.

String format = "x:y";
String string = "Marty:McFly";

Then

String x = "Marty";
String y = "McFly";

but the format can be anything it could look like this y?x => McFly?Marty

How to solve this using regex?

Edit: current solution

        String delimiter = format.replace(Y, "");
        delimiter = delimiter.replaceAll(X, "");
        delimiter = "\\"+delimiter;

        String strings[] = string.split(delimiter);

        String x; 
        String y;
        if(format.startsWith(X)){
             x = strings[0];
             y = strings[1];
        }else{
             y = strings[0];
             x = strings[1];
        }

        System.out.println(x);
        System.out.println(y);

This works well, but I would prefer more clean solution.

标签: javaregex

解决方案


根本不需要正则表达式。

public static void main(String[] args) {
    test("x:y", "Marty:McFly");
    test("y?x", "McFly?Marty");
}
public static void test(String format, String input) {
    if (format.length() != 3 || Character.isLetterOrDigit(format.charAt(1))
                             || (format.charAt(0) != 'x' || format.charAt(2) != 'y') &&
                                (format.charAt(0) != 'y' || format.charAt(2) != 'x'))
        throw new IllegalArgumentException("Invalid format: \"" + format + "\"");
    int idx = input.indexOf(format.charAt(1));
    if (idx == -1 || input.indexOf(format.charAt(1), idx + 1) != -1)
        throw new IllegalArgumentException("Invalid input: \"" + input + "\"");
    String x, y;
    if (format.charAt(0) == 'x') {
        x = input.substring(0, idx);
        y = input.substring(idx + 1);
    } else {
        y = input.substring(0, idx);
        x = input.substring(idx + 1);
    }
    System.out.println("x = " + x);
    System.out.println("y = " + y);
}

输出

x = Marty
y = McFly
x = Marty
y = McFly

如果可以将格式字符串更改为正则表达式,那么使用命名捕获组将使其变得非常简单:

public static void main(String[] args) {
    test("(?<x>.*?):(?<y>.*)", "Marty:McFly");
    test("(?<y>.*?)\\?(?<x>.*)", "McFly?Marty");
}
public static void test(String regex, String input) {
    Matcher m = Pattern.compile(regex).matcher(input);
    if (! m.matches())
        throw new IllegalArgumentException("Invalid input: \"" + input + "\"");
    String x = m.group("x");
    String y = m.group("y");
    System.out.println("x = " + x);
    System.out.println("y = " + y);
}

与上面相同的输出,包括值顺序。


推荐阅读