I'm in the middle of doing some string manipulation in Java. It just occurred to me, as I debugged an error in my code, that the String#replace takes a literal character sequence (i.e. another String) but the String#split takes a regex. This caused a small bug in the code I was writing as I had naively assumed that #replace was consistent with #split and took a regex. Thus I was passing in a regular expression rather than a string literal. The result was the string sequence I wanted to replace wasn't being replaced
public String[] thisIsBrokenCosReplaceTakesAStringLiteral(String value)
{
return value.replace("\\.", " ").split("[a-z]");
}
public String[] itShouldLookLikeThis(String value)
{
return value.replace(".", " ").split("[a-z]");
}
Perhaps it is a result of legacy, since other "replace" methods, such as #replaceAll and #replaceFirst take regexs too. It occurred to me that it would have been nice, for consistency, if #replace took a regex rather than a string literal. Perhaps there is a good reason for this?
Comments ...