Home > Enterprise >  Java; Splitting a string into segments
Java; Splitting a string into segments

Time:11-13

(Warning - made with Google Translate)

I am learning to use regular expressions while creating a simple program for myself that would take as input a string consisting of formulas for various dice rolls and modifiers to them. Example:

2d6 13 3d10-1d4 5 1d8-6

I have a regular expression to search for segments like " -XdY":

(^|[\\ -])[1-9]\\d*d[1-9]\\d*

I want to cut such segments from a string, store them as an array for further processing, and at the same time remove them from the string

Input - string "2d6 13 3d10-1d4 5 1d8-6"

Output - string " 13 5-6" (without any -XdY) and array of strings {"2d6", " 3d10", "-1d4", " 1d8"} (all of -XdY)

so after that it can be repeated with modifiers (using another regex)

Input - string " 13 5-6"

Output - string "" and array of strings {" 13", " 5", "-6"}

and, by the remaining string at the end, understand whether the data was entered correctly or not (empty = good).

The problem is that I simply cannot find a suitable tool to cut certain fragments from the string and save them as an array.

Can you help me? Or perhaps there is a simpler algorithm for this task?

Thanks for your help in advance!

CodePudding user response:

Split before or -:

String[] parts = str.split("(?=[ -])");

Test code:

String str = "2d6 13 3d10-1d4 5 1d8-6";
String[] parts = str.split("(?=[ -])");
System.out.println(Arrays.toString(parts));

Output:

[2d6,  13,  3d10, -1d4,  5,  1d8, -6]
  • Related