Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Split String Consecutive Delimiters

Tags:

java

regex

I have a need to split a string that is passed in to my app from an external source. This String is delimited with a caret "^" and here is how I split the String into an Array

String[] barcodeFields = contents.split("\\^+");

enter image description here

This works fine except that some of the passed in fields are empty and I need to account for them. I need to insert either "" or "null" or "empty" into any missing field.

And the missing fields have consecutive delimiters. How do I split a Java String into an array and insert a string such as "empty" as placeholders where there are consecutive delimiters?

like image 654
Val Okafor Avatar asked Jul 31 '15 16:07

Val Okafor


2 Answers

The answer by mureinik is quite close, but wrong in an important edge case: when the trailing delimiters are in the end. To account for that you have to use:

contents.split("\\^", -1)

E.g. look at the following code:

final String line = "alpha ^beta ^^^";
List<String> fieldsA = Arrays.asList(line.split("\\^"));
List<String> fieldsB = Arrays.asList(line.split("\\^", -1));
System.out.printf("# of fieldsA is: %d\n", fieldsA.size());
System.out.printf("# of fieldsB is: %d\n", fieldsB.size());

The above prints:

# of fieldsA is: 2
# of fieldsB is: 5
like image 160
Marcus Junius Brutus Avatar answered Sep 21 '22 06:09

Marcus Junius Brutus


String.split leaves an empty string ("") where it encounters consecutive delimiters, as long as you use the right regex. If you want to replace it with "empty", you'd have to do so yourself:

String[] split = barcodeFields.split("\\^");
for (int i = 0; i < split.length; ++i) {
    if (split[i].length() == 0) {
        split[i] = "empty";
    }
}
like image 41
Mureinik Avatar answered Sep 21 '22 06:09

Mureinik