简体   繁体   中英

Split with different delimiters JAVA

Lets say I have this kind of data:

"IAB98D Daewoo Cielo 15487964 PARABRISAS TRA"

"TAI64A Fiat Siena 13283191 PARACHOQUE DEL-CAPOT"

"RAD34B Toyota Corolla 11934274 TECHO-PUERTA TRA IZQ"

Where: 1st element = the car's ID - 2nd element = brand of the car - 3rd element = model of the car - 4th element = owner's ID - 5th element and beyond separated by a "-" are the damaged parts of the car

Thing is when I use .split(" ") works fine for the first fourth elements but in the damaged parts is where things gets tricky for example in this 2nd array part "PARACHOQUE DEL-CAPOT" that means there are 2 damaged parts "PARACHOQUE DEL" and "CAPOT" if I use .split(" ") it will separate "PARACHOQUE DEL" to "PARACHOQUE" and "DEL" and I don't want that to happen because that's just 1 damaged part is there any way to achieve this? or any recommendations? Thanks in advance!

You can accomplish this with 2 calls to split , the first one limiting the fields to 5 fields: the first 4 fields and the damaged parts.

The first call to split is the two-arg overload of split , with a limit.

This code takes advantage of the fact that limiting the fields piles the remaining part of the original string, even if there are more separators, into the last element.

String line = "TAI64A Fiat Siena 13283191 PARACHOQUE DEL-CAPOT";
String[] fields = line.split("\\s+", 5);
System.out.println(Arrays.toString(fields));

This will generate the 5 fields for you:

[TAI64A, Fiat, Siena, 13283191, PARACHOQUE DEL-CAPOT]

The second call to split is the one-arg overload of split . Then you can split the last element on "-" to extract the damaged parts.

String damaged = fields[4];
String[] parts = damaged.split("-");
System.out.println(Arrays.toString(parts));

This outputs:

[PARACHOQUE DEL, CAPOT]

You will need to ensure that there are really 5 elements in the fields array before using index 4 .

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