【问题标题】:Split string by array of characters按字符数组拆分字符串
【发布时间】:2013-08-30 07:24:18
【问题描述】:

我想通过字符数组分割一个字符串, 所以我有这个代码:

String target = "hello,any|body here?";
char[] delim = {'|',',',' '};
String regex = "(" + new String(delim).replaceAll("(.)", "\\\\$1|").replaceAll("\\|$", ")");
String[] result = target.split(regex);

一切正常,除非我想在 delim[] 数组中添加像“Q”这样的字符, 它抛出异常:

java.util.regex.PatternSyntaxException: Illegal/unsupported escape sequence near index 11
(\ |\,|\||\Q)

那么我怎样才能修复它以使用非特殊字符呢?

提前致谢

【问题讨论】:

    标签: java regex arrays split


    【解决方案1】:

    我怎样才能修复它以使用非特殊字符以及

    在你的字符周围加上方括号,而不是转义它们。确保如果 ^ 包含在您的字符列表中,您需要确保它不是第一个字符,或者如果它是列表中唯一的字符,则将其单独转义。

    破折号也需要特殊处理——它们需要放在正则表达式的开头或结尾。

    String delimStr = String(delim);
    String regex;
    if (delimStr.equals("^") {
        regex = "\\^"
    } else if (delimStr.charAt(0) == '^') {
        // This assumes that all characters are distinct.
        // You may need a stricter check to make this work in general case.
        regex = "[" + delimStr.charAt(1) + delimStr + "]";
    } else {
        regex = "[" + delimStr + "]";
    }
    

    【讨论】:

      【解决方案2】:

      使用Pattern.quote 并将其放在方括号中似乎可行:

      String regex = "[" + Pattern.quote(new String(delim)) + "]";
      

      Tested with possible problem characters.

      【讨论】:

      • +1 不知道我们可以安全地使用像[\Qdelims\E] 这样的东西。打算发布类似的东西,但有更多的逻辑测试,但这是最简单的答案。
      【解决方案3】:

      Q 不是正则表达式中的控制字符,因此您不必将\\ 放在它之前(它仅用于标记您必须将以下字符解释为文字,而不是控件字符)。

      例子

      `\\.` in a regex means "a dot"
      
      `.` in a regex means "any character"
      

      \\Q 失败,因为Q 不是正则表达式中的特殊字符,因此不需要引用。

      我会将delim 设为一个字符串数组,并将引号添加到需要它的这些值中。

       delim = {"\\|", ..... "Q"};
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-04-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-01-07
        • 1970-01-01
        相关资源
        最近更新 更多