将一行移动到字符串的开头

时间:2016-09-28 14:57:30

标签: java regex string

我尝试运行此测试:

@Test
public void moveLastUpdateToFirstLine() throws Exception {
    StringUtils stringUtils = new StringUtils();
    String newString = stringUtils.moveLastUpdateToFirstLine("bbbbbbb last_update : 188908098 cccc");
    assert (newString.equals("last_update : 188908098 bbbbbbb cccc"));
}



public String moveLastUpdateToFirstLine(String venueConfigurationStr) {
    Pattern pattern = Pattern.compile("(last_update : \\d+)");
    Matcher matcher = pattern.matcher(venueConfigurationStr);

    if (matcher.find()) {
        venueConfigurationStr = matcher.group(1) + venueConfigurationStr.replace(matcher.group(1), "");
    }
    return venueConfigurationStr;
}

但它说:

java.lang.IllegalStateException: No match found

at java.util.regex.Matcher.group(Matcher.java:536)

我如何修复我的匹配器?

1 个答案:

答案 0 :(得分:0)

你的代码很好,除了它太多了。试试这个:

public String moveLastUpdateToFirstLine(String venueConfigurationStr) {
    return venueConfigurationStr.replaceAll("(.*)(last_update : \\d+ )(.*)", "$2$1$3");
}

注意:这也解决了代码中有关空格的错误。