简体   繁体   中英

Java Split String Consecutive Delimiters

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("\\^+");

在此处输入图片说明

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?

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";
    }
}

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)

Eg 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

Using ^+ means one (or more consecutive) carat characters. Remove the plus

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

and it won't eat empty fields. You'll get (your requested) "" for empty fields.

The following results in [blah, , bladiblah, moarblah] :

    String test = "blah^^bladiblah^moarblah";
    System.out.println(Arrays.toString(test.split("\\^")));

Where the ^^ are replaced by a "" , the empty String

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM