What a good way to split a string without delimiters in Java?

I want to split the lines as EADGBE or DADF # AD into separate lines, each of which contains one letter or one letter plus the # sign. Is there a more elegant way than repeating a line using brute force approach?

String.split obviously relies on delimiters, which are then discarded, which is not very useful for me - in a couple of minutes I thought it split("[a-gA-G]#?");would work, but no, it does not help at all - I almost want the opposite of this ...

+5
source share
4 answers

Most likely, your best option is both in terms of code and in terms of performance.

Alternatively you can use 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());
+3

, :

  String s = "DADF#AD"; 
  Pattern p = Pattern.compile("([a-gA-G]#?)");
  Matcher matcher = p.matcher(s);
  while (matcher.find()) {
      System.out.println(matcher.group());
  }
+1

lookahead lookbehind : String regex = "(?<=.)(?=\\w#?)";

.

import java.util.Arrays;

public class Foo {
   public static void main(String[] args) {
      String[] tests = {"EADGBE", "DADF#AD"};
      String regex = "(?<=.)(?=\\w#?)";
      for (String test : tests) {
         System.out.println(Arrays.toString(test.split(regex)));
      }
   }
}

:

[E, A, D, G, B, E]
[D, A, D, F #, A, D]

+1

How about this: add separators, then split:

Separators are added in this method.

private static String delimit(String in) {
  StringBuilder sb = new StringBuilder();
  for (int i = 0; i < in.length()-1; i++) {
    sb.append(in.charAt(i));
    if (in.charAt(i+1) != '#')
      sb.append(';');
  }
  return sb.toString();
}

To use it:

String[] notes = delimit("DADF#AD").split(";");
0
source

All Articles