gpt4 book ai didi

java - 如何增强 Java 模式,使其在匹配项周围也包含特殊字符?

转载 作者:行者123 更新时间:2023-11-30 06:35:00 25 4
gpt4 key购买 nike

我有一个如下所示的字符串:

*to *make/to *have *a *dab *at *smb. (\*dictionary) some text without special symbols at the begging.

目标是从字符串中提取以 * 符号开头的单词,这是我的做法:

Matcher matcher = Pattern.compile("[*]\\s*(\\w+)").matcher(input);
while (matcher.find()) {
phrase += matcher.group(1) + " ";
}

输出如下:

to make have a dab at smb dictionary

我确实理解为什么不包含括号(它们与模式不匹配),但是有人可以向我解释为什么 /to 部分不匹配吗?

是否有办法增强我的模式,使其在匹配项周围包含特殊字符(如果存在)?

预期输出:

to make/to have a dab at smb. (dictionary)

最佳答案

您可以使用此正则表达式与 2 个捕获组来查找 * 之前和之后的所有非空白文本。

(\S*)\*\s*(\S+)

RegEx Demo

您需要组合.group(1)一个.group(2)里面while循环。

对于 Java,请使用此正则表达式声明:

final String regex = "(\\S*)\\*\\s*(\\S+)";

关于java - 如何增强 Java 模式,使其在匹配项周围也包含特殊字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45358410/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com