【问题标题】:Split String deppending on characters in Java根据Java中的字符拆分字符串
【发布时间】:2019-04-24 14:21:48
【问题描述】:

给出以下字符串(一行):

a_Type_of_Data 0.847481:611x569+446+1200,0.515323:597x762+448+1101,0.587354:597x558+488+1207

我想这样拆分 [611, 559, 446 ,1200], [597, 762, 448, 1101], [597, 558, 488, 1207] 所以基本上要得到每个“:”和“,”之间的4个数字,而不考虑数字之间的字符。

我已经尝试在“,”上拆分字符串,但是我仍然遇到“:”前面的数字的问题。或者全部一起使用string result = Regex.Replace(input, @"[^\d]", "");

有没有办法用正则表达式来做到这一点? 提前致谢。

【问题讨论】:

  • "," 传递给split 对我来说似乎是正确的方法。然后将正则表达式 "([\\d.]*\\d):(\\d+)x(\\d+)\\+(\\d+)\\+(\\d+)" 应用于 split 返回的数组的每个元素。
  • 转义序列无效

标签: java regex string split


【解决方案1】:

您可以先使用此正则表达式\d+x\d+(?:\+\d+){2} 匹配由x+ 分隔的数字,然后使用[x+] 拆分这些单独的字符串,这将为您提供另一个数字数组。

检查此 Java 代码,

String s = "a_Type_of_Data 0.847481:611x569+446+1200,0.515323:597x762+448+1101,0.587354:597x558+488+1207";
Pattern p = Pattern.compile("\\d+x\\d+(?:\\+\\d+){2}");
List<List<String>> list = new ArrayList<>();

Matcher m = p.matcher(s);
while(m.find()) {
    String[] data = m.group().split("[x+]");
    list.add(Arrays.asList(data));
}
list.forEach(System.out::print);

按预期打印输出,

[611, 569, 446, 1200][597, 762, 448, 1101][597, 558, 488, 1207]

【讨论】:

    【解决方案2】:

    使用Matcher 及其 .find() 方法:

    package so21090424;
    
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    public class PatternFinder {
    
        public static void main(String[] args) {
            final String input = "a_Type_of_Data 0.847481:611x569+446+1200,0.515323:597x762+448+1101,0.587354:597x558+488+1207";
            Pattern p = Pattern.compile(":([0-9]+)[x\\+]([0-9]+)[x\\+]([0-9]+)[x\\+]([0-9]+),?");
            Matcher m = p.matcher(input);
            while(m.find()) {
                System.out.println(m.group(1) + "\t" + m.group(2) + "\t" + m.group(3) + "\t" + m.group(4));
            }
        }
    
    }
    
    

    【讨论】:

      【解决方案3】:
      String input = "a_Type_of_Data 0.847481:611x569+446+1200,0.515323:597x762+448+1101,0.587354:597x558+488+1207";
      
      List<List<String>> result = Arrays.stream(input.split(","))        // split input at ','
             .map(e->e.split(":")[1])                                    // split each part at ':' and keep the second part
             .map(e->Pattern.compile("[+x]").splitAsStream(e).collect(Collectors.toList()))    // split at '+' or 'x' & collect to list 
             .collect(Collectors.toList());                            // collect to list 
      System.out.println(result);
      

      【讨论】:

        最近更新 更多