I want to split strings in the form of EADGBE or DADF#AD into separate strings, each containing either one letter or one letter plus a # sign. Is there any more elegant way than iterating through the string with a brute-force sort of approach?
String.split obviously relies on delimiters, which are then discarded, which is not much use to me at all - for a couple of minutes there I thought split("[a-gA-G]#?");
was going to work, but no, that doesn't help at all - I almost want the opposite of that...
Brute force is likely to be your best option, both in terms of code and performance.
Alternatively, you could use a Matcher
Pattern p = Pattern.compile("[a-gA-G]#?");
Matcher m = p.march(inputString);
List<String> matches = new ArrayList<String>();
while(m.find())
matches.add(m.group());
If you forsee changes in pattern you can use:
String s = "DADF#AD";
Pattern p = Pattern.compile("([a-gA-G]#?)");
Matcher matcher = p.matcher(s);
while (matcher.find()) {
System.out.println(matcher.group());
}
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