【问题标题】:Java split a string to get only alphanumeric (but not alpha or numeric)Java拆分字符串以仅获取字母数字(但不是字母或数字)
【发布时间】:2015-04-09 14:42:32
【问题描述】:

目前我有以下代码:

String test = "=(7+A15)-5";
if(test.matches(".*[A-z]+[0-9]+.*")){
    String spl[] = test.split("((?<=[A-z]{1,4}[0-9]{1,4})|(?=[A-z]{1,4}[0-9]{1,4}))",3);
    System.out.println(spl[0] + "\n" + spl[1] +  "\n" +spl[2] );            
}

打印我:

=(7+
A1
5)-5

除非我想要:

=(7+
A15
)-5

但我不知道为什么当我问 {1,4} 时它只得到一个数字

【问题讨论】:

  • [A-z] 包括字符 '[', '\\', ']', '^', '_','`'。在new String("foo") 中包装字符串是没有意义的。
  • 字母数字标记的范围是多少(从您的正则表达式看来,您正在查看每个字母的 1 到 4 个 {1,4} 和每个数字的 {1,4}。ABCD1234 是有效但 ABCDEF12345 无效?
  • 没错,ABCD1234 有效,而 ABCDEF... 无效
  • @Naouk 得到了一个解决方案,尽管它很奇怪.....
  • 你能分享一下吗@gtgaxiola?我尝试了很多东西,但找不到。我需要保留分隔符,如果它没有正确拆分,则没有任何作用

标签: java regex split alphanumeric


【解决方案1】:

我会使用分隔符,例如

String delimiter = "[a-zA-Z]{1,4}[0-9]{1,4}";

然后同时执行lookaheadlookbehind 以捕获分隔符以及要拆分的标记。

//Lookahead and lookbehind where %1 is the delimiter
String WITH_DELIMITER = "((?<=%1$s)|(?=%1$s))";
String regex = String.format(WITH_DELIMITER, delimiter);

因为看起来捕获组在匹配正则表达式的那一刻就分裂了

示例:A15 被拆分为 A 15

您需要遍历您的标记以连接那些实际上是分隔符的标记(使用不同的匹配器)

String matcher = "[a-zA-Z]*[0-9]+";
String[] s = text.split(regex);
List<String> result = new ArrayList<>();
String tmp = "";
for (String x : s) {
    if (x.matches(matcher)) {
        tmp += x;
    } else {
        if (!tmp.isEmpty()) {
            result.add(tmp);
            tmp = "";
        }
        result.add(x);
    }
}
if(!tmp.isEmpty()) {
    result.add(tmp);
}

把它们放在一起:

public static List<String> splitWithDelimiter(String text, String delimiter) {
    String WITH_DELIMITER = "((?<=%1$s)|(?=%1$s))";
    String regex = String.format(WITH_DELIMITER, delimiter);
    String matcher = "[a-zA-Z]*[0-9]+";
    String[] s = text.split(regex);
    List<String> result = new ArrayList<>();
    String tmp = "";
    for (String x : s) {
        if (x.matches(matcher)) {
            tmp += x;
        } else {
            if (!tmp.isEmpty()) {
                result.add(tmp);
                tmp = "";
            }
            result.add(x);
        }
    }
    if(!tmp.isEmpty()) {
        result.add(tmp);
    }
    return result;
}

public static void main(String[] args) {
    String test = "=(7+A185)-5";
    String delimiter = "[a-zA-Z]{1,4}[0-9]{1,4}";
    List<String> s = splitWithDelimiter(test, delimiter);
    for (String x : s) {
        System.out.println(x);
    }
}

哪些输出:

=(7+
A185
)-5

【讨论】:

    猜你喜欢
    • 2015-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多