0

Given this string:

String number = "1234*987-654";

I want split and store in string array like [1234, *, 987, -, 654]

How I achieve this?

shmosel
  • 49,289
  • 6
  • 73
  • 138

1 Answers1

1

You could try splitting using lookarounds:

(?<=\D)(?=\d)|(?<=\d)(?=\D)

Sample script:

String number = "1234*987-654";
String[] parts = number.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");
System.out.println(Arrays.toString(parts));
// [1234, *, 987, -, 654]

The logic here it split at the interface between any non digit and digit character, or vice-versa. Note that because we split using purely lookarounds, no characters actually get consumed.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • 1
    Looks [familiar](https://stackoverflow.com/questions/27808112/java-splitting-with-math-expression) ‍♂️ – Bohemian May 23 '21 at 05:49
  • @Bohemian For the record, I never have ever seen your answer, what I wrote above is my own content alone. – Tim Biegeleisen May 23 '21 at 05:53
  • 1
    I don’t doubt your integrity, ever. LOL I didn’t realise I answered the dupe when I duped this Q out. But I knew there were dupes out there and just found this first one that matches. Nevertheless, this is a well worn question. – Bohemian May 23 '21 at 05:56
  • Agreed on the dupe...of _something_. Then again, it's Sunday on SO. You have two choices: answer less than perfect questions, or get no points haha `:-)` – Tim Biegeleisen May 23 '21 at 05:57
  • **Thank you friends. I solved finally with your help. Have a nice day** – Nikhil apps May 23 '21 at 10:25