繁体   English   中英

字符串拆分特殊正则表达式

[英]String split special regular Expression

我试图标记一个字符串输入,但是我无法理解该怎么做。 想法是将字符串拆分为字母单词和非字母符号的实例。 例如,字符串"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());
}

输出量

Test , ( abc ) ,希望它能回答您的问题。

尝试这个:

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());
}

输出:

I
want
to
walk
my
dog
,
and
why
not
?

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

(摘自: 这里

尝试这个:

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;
    }

我想以最简单的形式使用

"(?<=[a-zA-Z])(?=[^\\sa-zA-Z])|(?<=[^\\sa-zA-Z])(?=[a-zA-Z])|\\s+"

讲解

    (?<= [a-zA-Z] )               # Letter behind
    (?= [^\sa-zA-Z] )             # not letter/wsp ahead
 |                              # or,
    (?<= [^\sa-zA-Z] )            # Not letter/wsp behind
    (?= [a-zA-Z] )                # letter ahead
 |                              # or,
    \s+                           # whitespaces (disgarded)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM