【问题标题】:How Split String in android containing number如何在包含数字的android中拆分字符串
【发布时间】:2023-03-14 11:10:01
【问题描述】:

我有包含数字的动态字符串,例如如何从数字开始分隔

Golden Apples Perlim 1.000 kg

我想拆分Golden Apples Perlim1.000 kgLemon 1.000 kg 我想拆分 Lemon1.000 kg 分开

我怎样才能做到这一点?

【问题讨论】:

    标签: java android string split


    【解决方案1】:

    您可以使用正则表达式拆分:

    String input = "Golden Apples Perlim 1.000 kg";
    String[] parts = input.split("\\s+(?=\\d(?:\\.\\d+)?)");
    for (String part : parts) {
        System.out.println(part);
    }
    

    打印出来:

    Golden Apples Perlim
    1.000 kg
    

    【讨论】:

      【解决方案2】:

      您还可以将 Pattern 和 Matcher 与此正则表达式 (\D+?)(\d.*) 一起使用:

      String[] strs = {"Golden Apples Perlim 1.000 kg", "Lemon 1.000 kg"};
      Pattern pattern = Pattern.compile("(\\D+?)(\\d.*)");
      Matcher matcher;
      for (String str : strs) {
        matcher = pattern.matcher(str);
        if (matcher.find()){
          System.out.println(matcher.group(1));
          System.out.println(matcher.group(2));
        }
      }
      

      输出

      Golden Apples Perlim 
      1.000 kg
      Lemon 
      1.000 kg
      

      【讨论】:

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