java - 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
和应用格式。
解决方案
推荐阅读
- java - 方法中的参数, Object... VS Object[] ,这两者是否具有相同的功能?
- javascript - 如何使用一键登录获取已在我的 Web 应用程序上注册的所有用户的访问令牌
- node.js - 使用 Yarn Workspaces 在 monorepo 中可重复构建 Lambda 层
- c++ - Boost Spirit调试输出不出现
- java - 画圈
- c - 如何阻止 c 编程舍入小数位
- c++ - CMAKE 删除 lib 并使用 prebuild one
- html - 如何使文本相对于按钮居中,但不在容器中居中?
- spring - Spring Integration:发布/订阅:订阅者是否有办法让消息为它排队,即使它暂时处于非活动状态?
- mongodb - 如何在 Mongo 服务器端 javascript 中使用二进制或 UUID 类型?