Elad Benda Elad Benda - 2 months ago 9
Java Question

move a line to the beginning of a string

I try to run this test:

@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;
}


but it says:

java.lang.IllegalStateException: No match found

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


how can i fix my matcher?

Answer

Your code is fine, except there's too much of it. Try this instead:

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

Note: This also fixes the bug you have in your code regarding spaces.

Comments