• Sun
    August 12, 2011

Tip #5 Avoid RegEx When Unnecessary

I see this in GlassFish source code frequently:

string = string.replaceAll("\\\\", "/");

 Whoa!  FOUR backslashes?!?  Yes.  That's a regular expression.  What we see is FOUR but inside the string itself are TWO literal actual backslashes. The backslashes have to be doubled so that the RegEx parser knows that we are looking for a literal backslash.

What the author of this code really wants to do is something like this:

c:\a\b\c\d  ==>  c:/a/b/c/d

 This can easily be done without the more confusing regex notation and (I assume) the slower regex code like so:

string = string.replace('\\', '/');

Join the discussion

Comments ( 2 )
  • guest Friday, August 12, 2011

    your tip is titled "avoid RegEx when unnecessary" but your example does not avoid regex, it simply shows a cleaner regex. It's still the same regex.

  • guest Friday, September 30, 2011

    The code I recommended scans through the String once replacing every backslash with a slash. No regular expressions necessary.

Please enter your name.Please provide a valid email address.Please enter a comment.CAPTCHA challenge response provided was incorrect. Please try again.