【问题标题】:Can't find the right regex to split after the space that follows a commata在逗号后面的空格后找不到要拆分的正确正则表达式
【发布时间】:2012-05-09 19:20:17
【问题描述】:

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

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

给我数组

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

我真正想要的是

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

谁能帮帮我?

【问题讨论】:

  • @BenjaminUdinktenCate:现在将其发布为答案 :)

标签: java regex string split


【解决方案1】:

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

http://ideone.com/W8SaL

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

另外,你打错了goddman

【讨论】:

  • 如果字符串用逗号分隔,后跟多个空格,这将不起作用。
【解决方案2】:

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

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    "

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-20
    相关资源
    最近更新 更多