0

I have numbers and to want to split it to list of string using special character on it and with out removing special character on it like split

1,245.00
to
1
,
245
.
00
  • 1
    Hint: [`Character.isDigit()`](https://docs.oracle.com/javase/8/docs/api/java/lang/Character.html#isDigit-char-) – jmj Oct 03 '17 at 06:39
  • 1
    [`str.split("\\b")`](https://ideone.com/09yDNv) – 4castle Oct 03 '17 at 06:43
  • 1
    @4castle Nice answer, but perhaps if the OP would want to split at certain types of non word boundary characters then this might not work as planned. – Tim Biegeleisen Oct 03 '17 at 06:47
  • 1
    Refer this question, https://stackoverflow.com/questions/4416425/how-to-split-string-with-some-separator-but-without-removing-that-separator-in-j – Krishnan Oct 03 '17 at 06:47

2 Answers2

1

Split your string using lookaheads:

String input = "1,245.00";
String[] parts = input.split("(?=[^A-Za-z0-9])|(?<=[^A-Za-z0-9])");
for(String part : parts) {
    System.out.println(part);
}

This splits if, at any position is the string, either the preceding or proceeding character be a non letter or number.

Output:

1
,
245
.
00

Demo here:

Rextester

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

There are multiple options available. You can use the boundary (credits to @4castle), but also lookahead (credits to the previous reply) and lookbehind.

Here are three options which all work:

String input = "1,245.00";
// look-ahead only
Stream.of(input.split("(?=[,.])|(?<=[^\\d])")).forEach(System.out::println);
System.out.println();
// Boundary
Stream.of(input.split("\\b")).forEach(System.out::println);
System.out.println();
// Mix of look-behind and look-ahead
Stream.of(input.split("(?![\\d])|(?<=[^\\d])")).forEach(System.out::println);

All print together:

1
,
245
.
00

1
,
245
.
00

1
,
245
.
00
gil.fernandes
  • 12,978
  • 5
  • 63
  • 76