我正在尝试对字符串输入进行标记,但我无法弄清楚如何做到这一点。
想法是将字符串拆分为字母单词和非字母符号的实例。
例如字符串 "Test, ( abc)"
将分为 ["Test" , "," , "(" , "abc" , ")" ].
现在我使用这个正则表达式:
"(?<=[a-zA-Z])(?=[^a-zA-Z])"
但它没有达到我想要的效果。
还有什么想法我还可以使用吗?
最佳答案
我发现您想要对字母进行分组(例如 Test 和 abc),但不对非字母字符进行分组。我还发现您不想显示空格字符。为此,我将在从字符串中删除所有空格后使用 "(\\w+|\\W)"
进行匹配。
示例代码
String str = "Test, ( abc)";
str = str.replaceAll(" ",""); // in case you do not want space as separate char.
Pattern pattern = Pattern.compile("(\\w+|\\W)");
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
System.out.println(matcher.group());
}
输出
测试
,
(
ABC
)
我希望这回答了你的问题。
关于java - 字符串分割特殊正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47980552/