Cannot find the correct regular expression to separate after a space following a comma

Im using string.split (regex), so cut my line after each ",", but I don't know how to cut after a space following ",".

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

gives me an array

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

I really want

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

can someone help me?

+3
source share
2 answers

Using a positive lookbehind will not allow you to match if the string is separated by multiple spaces.

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

Conclusion:

"I,    "
"am,       "
"the, "
"goddamn, "
"Batman    "
+1
source

Just add a space to your regex:

http://ideone.com/W8SaL

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

In addition, you are sealed goddman.

+2
source

All Articles