Reputation: 149
I have large String something like:
String = "ABC114.553111.325785.658EFG114.256114.589115.898";
I would like to achieve:
String1 = "ABC";
String2 = "114.553";
String3 = "111.325";
String4 = "785.658";
Sometimes it isn't three digits then dot and four digits after. But always Before digits there is three letters.
Upvotes: 1
Views: 533
Reputation: 17649
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));
}
}
Output:
ABC
114.553
111.325
785.658
EFG
114.256
114.589
115.898
Upvotes: 1
Reputation: 5120
You can use the following regexp:
([^\.]){3}(\....)?
Here a program...
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));
}
}
}
Output
found: ABC
found: 114.553
found: 111.325
found: 785.658
found: EFG
found: 114.256
found: 114.589
found: 115.898
Upvotes: 2
Reputation: 429
A bad option can be to loop over string 0 to n-4. and keep track of (i+3)th character, if it is ".", you know where to split - at "i".
@Matt - You lost strings of alphabets "ABC" and "EFG", those were supposed to be retained.
Upvotes: 0