Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's a good way to split a non-delimited string in Java?

Tags:

java

string

split

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...

like image 590
Oolong Avatar asked Mar 17 '12 22:03

Oolong


2 Answers

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());
like image 118
Guillaume Polet Avatar answered Sep 29 '22 08:09

Guillaume Polet


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());
  }
like image 20
Ashwinee K Jha Avatar answered Sep 29 '22 06:09

Ashwinee K Jha