regex_and_literals

Quick Profile

Alex Ooi Profile Picture
Hometown: Melbourne, Australia
Specializations: Java, Ruby on Rails
University: Software Engineering & Economics, Melbourne University
High School: VCE, Melbourne High School
Links:
 

Popular Articles

Friday, March 18, 2011

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 :(

broken



    public String[] thisIsBrokenCosReplaceTakesAStringLiteral(String value)
    {
        return value.replace("\\.", " ").split("[a-z]");
    }


works



    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 ...

Holy Guacamole! Nobody has commented on this post yet! Why don't you make a name for yourself and be the first to do so ... Any comment whatsoever, as long as it is non-defamatory, will be welcome!

Add a Comment

*
*
You must answer the following simple maths question before your comment will be accepted.
*