Java在自定义位置拆分字符串

Java在自定义位置拆分字符串,java,string,split,Java,String,Split,我有一根大绳子,像: String = "ABC114.553111.325785.658EFG114.256114.589115.898"; 我希望实现: String1 = "ABC"; String2 = "114.553"; String3 = "111.325"; String4 = "785.658"; 有时它不是三位数,然后是点,然后是四位数。但在数字之前总是有三个字母。一个不好的选择可能是在字符串0到n-4之间循环。并跟踪第(i+3)个字符,如果是“.”,您知道在哪里拆分-在

我有一根大绳子,像:

String = "ABC114.553111.325785.658EFG114.256114.589115.898";
我希望实现:

String1 = "ABC";
String2 = "114.553";
String3 = "111.325";
String4 = "785.658";

有时它不是三位数,然后是点,然后是四位数。但在数字之前总是有三个字母。

一个不好的选择可能是在字符串0到n-4之间循环。并跟踪第(i+3)个字符,如果是“.”,您知道在哪里拆分-在“i”处

String s = "ABC114.553111.325785.658EFG114.256114.589115.898";
Matcher prefixes = Pattern.compile("([A-Z]{3})").matcher(s);
for (String part : s.split("[A-Z]{3}")) {
    if (part.equals("")) {
        continue;
    }

    prefixes.find();
    System.out.println(prefixes.group(0));

    for (int i = 0; i < part.length(); i += 7) {
        System.out.println(part.substring(i, i + 7));
    }
}

@马特-您丢失了字母“ABC”和“EFG”的字符串,它们本应被保留。

您可以使用以下regexp:

([^\.]){3}(\....)?
这里有一个程序

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class C {

    public static void main(String[] args) {
        String a = "([^\\.]){3}(\\....)?";
        String b = "ABC114.553111.325785.658EFG114.256114.589115.898";

        Pattern pattern = Pattern.compile(a);
        Matcher matcher = pattern.matcher(b);

        while (matcher.find()) {
            System.out.println("found: " + matcher.group(0));
        }
    }
}
输出

found: ABC
found: 114.553
found: 111.325
found: 785.658
found: EFG
found: 114.256
found: 114.589
found: 115.898

你能描述一下模式吗?到目前为止,您所显示的内容和您所说的内容似乎没有遵循一种模式。是否可以在要拆分的字符串中插入一些字符?“有时不是三位数字,然后是点,然后是四位数字”-您如何区分此:
114.5533和111.3257
与此:
114.553和3111.3257
给定输入:
114.5533111.3257
?您唯一遗漏的是OP将字母指定为提示输出的一部分,我相应地更新了示例。
found: ABC
found: 114.553
found: 111.325
found: 785.658
found: EFG
found: 114.256
found: 114.589
found: 115.898