3

我使用 string.split(regex) 所以在每个“,”之后剪切我的字符串,但我不知道如何在“,”后面的空格之后剪切。

String content = new String("I, am, the, goddman, Batman");
content.split("(?<=,)");

给了我数组

{"I,"," am,"," the,"," goddman,"," Batman"}

我真正想要的是

{"I, ","am, ","the, ","goddman, ","Batman "}

谁能帮帮我?

4

2 回答 2

2

只需将空格添加到您的正则表达式中:

http://ideone.com/W8SaL

content.split("(?<=, )");

另外,你打错字了goddman

于 2012-05-09T19:23:47.207 回答
1

如果字符串用多个空格分隔,则使用正向向后查找将不允许您执行匹配。

public static void main(final String... args) {
    // final Pattern pattern = Pattern.compile("(?<=,\\s*)"); won't work!
    final Pattern pattern = Pattern.compile(".+?,\\s*|.+\\s*$");
    final Matcher matcher = 
                  pattern.matcher("I,    am,       the, goddamn, Batman    ");
    while (matcher.find()) {
        System.out.format("\"%s\"\n", matcher.group());
}

输出:

"I,    "
"am,       "
"the, "
"goddamn, "
"Batman    "
于 2012-05-09T20:09:05.953 回答