Java line separators

I need to break the string that is passed to my application from an external source. This string is limited to the caret "^" , and this is how I split String into an array

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

enter image description here

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

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

+4
source share
3 answers

String.split leaves an empty string ( "" ) where it encounters consecutive delimiters if you use the correct regular expression. If you want to replace it with "empty" , you have to do it yourself:

 String[] split = barcodeFields.split("\\^"); for (int i = 0; i < split.length; ++i) { if (split[i].length() == 0) { split[i] = "empty"; } } 
+3
source

Using ^+ means one (or more consecutive) carats. Remove plus

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

and he will not eat empty fields. You will receive (your request) "" for empty fields.

+1
source

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

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

If ^^ replaced with "" , an empty string

-one
source

All Articles