给定以下字符串(一行):
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]", "");
有没有办法用正则表达式做到这一点? 提前致谢。
最佳答案
您可以先使用此正则表达式 \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]
关于java - 根据 Java 中的字符拆分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55832370/