首页 > 解决方案 > Java 正则表达式 - 如何将字符串分成几部分

问题描述

我正在尝试将文本切成Array(或List)。例如String

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

应分为:

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

我解决了一些问题,regex例如:

Pattern用于查找我的匹配项的s:

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

我还发现了如何用我的模式分割文本:

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

这导致:

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

但我无法找到一种方法,而不会丢失模式的信息。

我为什么这样做?我需要使用将纯文本转换为格式化文本,javafx.scene.text.TextFlow因此我需要找到块并创建javafx.scene.text.Text和应用格式。

标签: javaregexjavafxtextflow

解决方案


推荐阅读