无法找到正确的正则表达式来在逗号后面的空格处进行分割(涉及IT技术)。

3
我正在使用 string.split(regex) 方法,以在每个逗号后分割我的字符串,但是我不知道如何在逗号后面的空格处分割。
String content = new String("I, am, the, goddman, Batman");
content.split("(?<=,)");

给我这个数组

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

what i actually want is

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

有人可以帮我吗?

这与IT技术无关。

1
@BenjaminUdinktenCate:现在把它发布为答案 :) - carlpett
2个回答

2
只需在你的正则表达式中添加空格即可: http://ideone.com/W8SaL
content.split("(?<=, )");

另外,您拼错了 goddman 这个单词。


如果字符串是用逗号后面跟着多个空格分隔的话,这样做不起作用。 - Sahil Muthoo

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    "

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接