I have a String in below format:
[string1][string2][string3][string4][string5][string6]
in which first string which is string1 will always be Year and it will be in this format YYYY so sample example is:
[2010][Toyota][ALL][Hatchback][998ccm 68HP 50KW]
Now in some cases, string1 is coming in this format 2010^K2011^K2012^K2013^K2014^K2015^K2016^K2017 in which each year is separated by ^K delimiter. Sample example:
[2010^K2011^K2012^K2013^K2014^K2015^K2016^K2017][Toyota][ALL][Hatchback][998ccm 68HP 50KW]
Now whenever I see strings in above format, I have to parse year string and split on the delimiter and extract each individual year and then make list of strings in this below format:
[2010][Toyota][ALL][Hatchback][998ccm 68HP 50KW]
[2011][Toyota][ALL][Hatchback][998ccm 68HP 50KW]
[2012][Toyota][ALL][Hatchback][998ccm 68HP 50KW]
[2013][Toyota][ALL][Hatchback][998ccm 68HP 50KW]
[2014][Toyota][ALL][Hatchback][998ccm 68HP 50KW]
[2015][Toyota][ALL][Hatchback][998ccm 68HP 50KW]
[2016][Toyota][ALL][Hatchback][998ccm 68HP 50KW]
[2017][Toyota][ALL][Hatchback][998ccm 68HP 50KW]
So I can think of below cases:
Is this possible to do? I know how to split a string on a special character ^ but confusion is how to extract string1 and check whether it has multiple years in it (if yes then split it) or it has only one year in it or it has something else.
public static void main(String[] args) {
// String myString =
// "[2010^K2011^K2012^K2013^K2014^K2015^K2016^K2017][Toyota][ALL][Hatchback][998ccm 68HP 50KW]";
String myString = "[2010][Toyota][ALL][Hatchback][998ccm 68HP 50KW]";
}
I have come up with this method:
public static String[] splitYears(String str) {
// get the year part of the string using a regex
Matcher m = Pattern.compile("^\\[([\\d^K]+)\\]").matcher(str);
if(m.find()) {
String yearPart = m.group(1);
// separate the other parts. The + 2 here is to account for the two square brackets in the yearPart
String otherParts = str.substring(yearPart.length() + 2);
// split by ^K
String[] years = yearPart.split("\\^K");
// Construct a new string for each year
String[] newYears = new String[years.length];
for (int i = 0; i < years.length; i++) {
newYears[i] = String.format("[%s]%s", years[i], otherParts);
}
return newYears;
} else {
return new String[] {str};
}
}
Usage:
System.out.println(Arrays.toString(splitYears("[2010^K2011^K2012^K2013^K2014^K2015^K2016^K2017][Toyota][ALL][Hatchback][998ccm 68HP 50KW]")));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With