我正在尝试重新创建 discord 解析消息的方式,其中包含表情符号。
例如,我希望将消息 Hello, :smile::hearth: world!
拆分为以下数组:
["Hello, ", ":smile:", ":hearth:", " world!"]
我已经尝试使用以下代码拆分数组:
Arrays.toString(message.split("(:[A-Za-z]+:)"))
但是,split 方法会删除找到的分隔符。所以最终结果是这样的:
["Hello", , , " world!"]
根据您的输入字符串和预期结果,我可以推断出您基本上想从三个规则中拆分您的字符串。
- 从前后加冒号的点开始拆分
- 从前面有一个空格,后面有一个冒号的点开始拆分
- 从前面有一个冒号后面有一个空格的点开始拆分
因此,对于上述所有三种情况,您可以通过交替使用此正则表达式。
(?<=:)(?=:)|(?<= )(?=:)|(?<=:)(?= )
Regex Demo
Java代码,
String s = "Hello, :smile::hearth: world!";
System.out.println(Arrays.toString(s.split("(?<=:)(?=:)|(?<= )(?=:)|(?<=:)(?= )")));
打印出您预期的输出,
[Hello, , :smile:, :hearth:, world!]
此外,作为替代方案,如果您可以使用匹配文本而不是拆分,则正则表达式使用起来会简单得多,就是这样,
:[^:]+:|\S+
Regex Demo using match
Java代码,
String s = "Hello, :smile::hearth: world!";
Pattern p = Pattern.compile(":[^:]+:|\\S+");
Matcher m = p.matcher(s);
while(m.find()) {
System.out.println(m.group());
}
打印,
Hello,
:smile:
:hearth:
world!