Trim a possible prefix of a string in Java

java, regex, string

Solution

Shorter than above code will be this line:

return str.replaceFirst("^abc", "");

But in terms of performance I guess there wont be any substantial difference between 2 codes. One uses regex and one doesn't use regex but does search and substring.

Problem

I have `String str`, from which I want to extract the sub-string excluding a possible prefix `"abc"`. The first solution that comes to mind is: ``` if (str.startsWith("abc")) return str.substring("abc".length()); return str; ``` My questions are: Is there a "cleaner" way to do it using `split` and a regular expression for an `"abc"` prefix? If yes, is it less efficient than the method above (because it searches "throughout" the string)? If yes, is there any better way of doing it (where "better way" = clean and efficient solution)? Please note that the `"abc"` prefix may appear elsewhere in the string, and should not be removed. Thanks

Original source