Java Regex捕获组包含空间,为什么?

时间:2012-07-07 09:42:56

标签: java regex

我正在尝试解析这个字符串,

"斬釘截鐵 斩钉截铁 [zhan3 ding1 jie2 tie3] /to chop the nail and slice the iron (idiom)/resolute and decisive/unhesitating/definitely/without any doubt/";

使用此代码

private static final Pattern TRADITIONAL = Pattern.compile("(.*?) ");

    private String extractSinglePattern(String row, Pattern pattern) {
        Matcher matcher = pattern.matcher(row);
        if (matcher.find()) {
            return matcher.group();
        }
        return null;
    }

但是,由于某种原因,返回的字符串在末尾包含一个空格

org.junit.ComparisonFailure: expected:<斬釘截鐵[]> but was:<斬釘截鐵[ ]>

我的模式有问题吗? 我也试过

private static final Pattern TRADITIONAL = Pattern.compile("(.*?)\\s");

但无济于事

我也尝试过匹配模式末尾的两个空格,但它不匹配(只有一个空格)。

2 个答案:

答案 0 :(得分:2)

您正在使用Matcher.group(),其记录为:

  

返回上一个匹配项匹配的输入子序列。

匹配包含空格。匹配中的捕获组没有,但您没有要求。

如果您将return语句更改为:

return matcher.group(1);

然后我相信它会做你想要的。

答案 1 :(得分:0)

使用此正则表达式(.+?)(?=\s+)