【问题标题】:split string to parts by regex通过正则表达式将字符串拆分为多个部分
【发布时间】:2015-01-14 09:51:16
【问题描述】:

我需要通过正则表达式将字符串拆分为多个部分。 字符串是:AA2 DE3 或 AA2,我需要这个 2。

String code = "AA2 DE3";
String[] parts = code.split("^(AA(\\d)+){1}( )?(\\w*)?$");

这里parts的长度为0。 我试过了

String[] parts = code.split("^((AA){1}(\\d)+){1}( )?(\\w*)?$");

但也是 0。

看起来像错误的正则表达式。虽然它在 PHP 中运行良好。

编辑

实际上我需要得到“AA”后面的数字,但后面可能会有额外的单词。

【问题讨论】:

标签: java regex


【解决方案1】:

假设您只想提取数字而不关心验证其余部分:

Pattern pattern = Pattern.compile("^AA(\\d+)");
Matcher matcher = pattern.matcher(code);

String id = null;

if (matcher.find()) {
    id = matcher.group(1);
}

请注意,我将 (\d)+ 重写为 (\d+) 以捕获所有数字。当有多个数字时,您的正则表达式仅捕获最后一个数字。

如果您想保留验证:

Pattern pattern = Pattern.compile("^AA(\\d+) ?\\w*$");

【讨论】:

    【解决方案2】:

    使用String.split,正则表达式指定各部分之间的内容。在您的情况下,您的正则表达式匹配整个字符串,因此没有其他内容,因此它什么也不返回。

    如果你想匹配这个正则表达式,使用:

    Pattern pattern = Pattern.compile("^(AA(\\d)+){1}( )?(\\w*)?$");
    Matcher matcher = pattern.matcher(code);
    if(!matcher.matches()) {
        // the string doesn't match your regex; handle this
    
    } else {
        String part1 = matcher.group(1);
        String part2 = matcher.group(2);
        // repeat the above line similarly for the third and forth groups
    
        // do something with part1/part2/...
    }
    

    【讨论】:

    • 它将在您的第 3 行抛出 IllegalStateException。您需要致电find() 或matches() 在这种情况下也可以。
    【解决方案3】:

    为此使用Pattern 和Matcher API 确实更好。

    这纯粹是出于学术目的,以防您只能使用String#split。您可以将这个基于后视的正则表达式用于split:

    (?<=AA\\d{1,999}) *
    

    代码:

    String[] toks = "AA2 DE3".split( "(?<=AA\\d{1,999}) *" ); // [AA2, DE3]
    

    或

    String[] toks = "AA2".split( "(?<=AA\\d{1,999}) *" ); // [AA2]
    

    【讨论】:

    • 题外话:嗨,很久了:) 还记得吗?我要在 Twitter 上加你。
    • @RaviThapliyal:你好吗?是的,请加我,我会欣然接受。
    • 我很好。到时候见,是时候实现某种消息传递了!
    【解决方案4】:

    如果您希望String#split() 为您处理模式/匹配器,您可以使用:

    String[] inputs = { "AA2 DE3", "AA3", "BB45 FG6", "XYZ321" };
        try {
            for (String input : inputs) {
                System.out.println(
                        input.split(" ")[0].split("(?=\\d+$)", 2)[1]
                    );
            }
        } catch (ArrayIndexOutOfBoundsException e) {
            System.err.println("Input format is incorrect.");
        }
    }
    

    输出:

    2
    3
    45
    321
    

    如果保证输入以AA开头,也可以使用

    System.out.println(
        input.split(" ")[0].split("(?<=^AA)")[1]
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-14
      • 1970-01-01
      • 1970-01-01
      • 2012-12-07
      • 1970-01-01
      • 2022-11-12
      • 1970-01-01
      • 2018-06-02
      相关资源
      最近更新 更多