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 に答える