Java使用正则表达式将字符串解析为变量

时间:2018-12-06 17:08:30

标签: java regex

我需要从字符串中提取变量。

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

然后

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

但是格式可以是任何看起来像y?x => McFly?Marty

的格式。

如何使用正则表达式解决此问题?

编辑:当前解决方案

        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);

这很好,但是我希望有更干净的解决方案。

2 个答案:

答案 0 :(得分:1)

根本不需要正则表达式。

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

如果可以将格式字符串更改为正则表达式,则使用named-capturing groups将使其非常简单:

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);
}

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

答案 1 :(得分:0)

您可以使用以下正则表达式(\\w)(\\W)(\\w)

这将找到任何字母数字字符,后跟任何非字母数字字符,再跟另一组字母数字字符。括号将对结果进行分组,因此组1将是参数1,组2将是定界符,组3将是参数2。

将参数1与参数2进行比较可以确定它们进入的词法顺序。

样品

  public static void main(String[] args)  {
    testString("x:y", "Marty:McFly");
    testString("x?y", "Marty?McFly");
    testString("y:x", "Marty:McFly");
    testString("y?x", "Marty?McFly");
  }

  /**
   * 
   */
  private static void testString(String format, String string) {
    String regex = "(\\w)(\\W)(\\w)";

    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(format);

    if (!matcher.find()) throw new IllegalArgumentException("no match found");

    String delimiter = matcher.group(2);

    String param1 = matcher.group(1); 
    String param2 = matcher.group(3); 


    String[] split = string.split("\\" + delimiter);
    String x;
    String y;
    switch(param1.compareTo(param2)) {
      case 1:
        x = split[1];
        y = split[0];
        break;
      case -1:
      case 0:
      default:
        x = split[0];
        y = split[1];
    };

    System.out.println("String x: " + x);
    System.out.println("String y: " + y);

    System.out.println(String.format("%s%s%s", x, delimiter, y));
    System.out.println();
  }

这种方法将允许您具有任何类型的格式,而不仅仅是x和y。您可以使用任何与正则表达式匹配的格式。

相关问题