Java regex - how to chop String into parts

45 Views Asked by At

I am trying to chop a text into an Array (or List). For example the String

String str = "so this will be _ITALIC_ and this will be *BOLD* and so on";

shall be split into this:

String[] arr = new String[] {"so this will be ", "_ITALIC_", " and this will be ", "*BOLD*", " and so on"};

i worked out some things with regex like:

the Patterns for finding my matches:

public static final Pattern Italic = Pattern.compile("_(.*?)_");
public static final Pattern Bold = Pattern.compile("\\*(.*?)\\*");
public static final Pattern Strike = Pattern.compile("~(.*?)~");

i also found out how to split the text with my patterns:

// more to be added
Pattern ptn = Pattern.compile(Italic + "|" + Bold + "|" + Strike);
String[] parts = ptn.split(input);

which results in:

"so this will be "
" and this will be "

but i am not able to find a way, without loosing the information of the pattern.

Why i do this? i need to transform plain text to formatted text using javafx.scene.text.TextFlow therefore i need to find the chunks and create javafx.scene.text.Text and apply the formating.

0

There are 0 best solutions below