A custom adaptation of Pattern#split(CharSequence, int). This is useful if the matched split-tokens should be returned as well. For example: split("e", "hello world") // ["h", "e", "llo world"] split("o", "hello world") // ["hell", "o", " w", "o", "rld"] split("[eo]", "
(String regex, CharSequence input)
| 1449 | * The result will always be an odd-length array. |
| 1450 | */ |
| 1451 | public static String[] split(String regex, CharSequence input) { |
| 1452 | int index = 0; |
| 1453 | ArrayList<String> matchList = new ArrayList<>(); |
| 1454 | Matcher m = Pattern.compile(regex).matcher(input); |
| 1455 | |
| 1456 | // Add segments before each match found |
| 1457 | while (m.find()) { |
| 1458 | matchList.add(input.subSequence(index, m.start()).toString()); |
| 1459 | matchList.add(input.subSequence(m.start(), m.end()).toString()); |
| 1460 | |
| 1461 | index = m.end(); |
| 1462 | } |
| 1463 | |
| 1464 | // If no match was found, return this |
| 1465 | if (index == 0) |
| 1466 | return new String[] { input.toString() }; |
| 1467 | |
| 1468 | // Add remaining segment |
| 1469 | matchList.add(input.subSequence(index, input.length()).toString()); |
| 1470 | |
| 1471 | // Construct result |
| 1472 | Iterator<String> it = matchList.iterator(); |
| 1473 | while (it.hasNext()) { |
| 1474 | if ("".equals(it.next())) { |
| 1475 | it.remove(); |
| 1476 | } |
| 1477 | } |
| 1478 | |
| 1479 | String[] result = new String[matchList.size()]; |
| 1480 | return matchList.toArray(result); |
| 1481 | } |
| 1482 | |
| 1483 | } |
no test coverage detected