String split特殊正则表达式

问题描述 投票:0回答:4

我试图标记字符串输入,但我无法理解如何做到这一点。想法是将字符串拆分为字母词和非字母符号的实例。例如,字符串"Test, ( abc)"将被拆分为["Test" , "," , "(" , "abc" , ")" ].

现在我使用这个正则表达式:qazxsw大便,但它没有做我想要的。

还有什么想法我还能用吗?

java regex string split
4个回答
2
投票

我看到你想要对字母表进行分组(比如Test和abc),但不要对非字母字符进行分组。另外我看到你不想显示空格char。为此,我将在删除字符串中的所有空格以匹配后使用"(?<=[a-zA-Z])(?=[^a-zA-Z])"

示例代码

"(\\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()); } 我希望这能回答你的问题。


0
投票

试试这个:

Test
,
(
abc
)

0
投票

试试这个:

public static ArrayList<String> res(String a) {
        String[] tokens = a.split("\\s+");
        ArrayList<String> strs = new ArrayList<>();
        for (String token : tokens) {
            String[] alpha = token.split("\\W+");
            String[] nonAlpha = token.split("\\w+");
            for (String str : alpha) {
                if (!str.isEmpty()) strs.add(str);
            }
            for (String str : nonAlpha) {
                if (!str.isEmpty()) strs.add(str);
            }
        }
        return strs;
    }

输出:

String s = "I want to walk my dog, and why not?";
Pattern pattern = Pattern.compile("(\\w+|\\W)");
Matcher matcher = pattern.matcher(s);
while (matcher.find()) {
    System.out.println(matcher.group());
}

\ w可用于匹配单词字符([A-Za-z0-9_]),以便从结果中删除标点符号

(摘自:I want to walk my dog , and why not ?


0
投票

我想用最简单的形式,拆分使用

here

解释

"(?<=[a-zA-Z])(?=[^\\sa-zA-Z])|(?<=[^\\sa-zA-Z])(?=[a-zA-Z])|\\s+"
© www.soinside.com 2019 - 2024. All rights reserved.