Reputation: 755
Can you remove leading-and-lagging characters-and-substrings from a string without using RegEx-and/or-Custom-Code?
For example, I want to remove leading https://
and lagging /
(backslashes).
I can definitely solve this with custom code and/or RegEx. But we don't want to go ahead with these answers after discussion. Many people are uncertain about this change and do not want to spend time learning RegEx to verify. We just want to make it easy and simple to switch-out and verify is working after refactoring. Is there there a package solution or built-in that already handles find-replace first-and-last?
@Value("${elsewhere.host.url:https://url.or.uri.full.or.partial}")
String urlOrUri;
// ...
String scheme = "https://"
// Example 1:
if (urlOrUri.startsWith(scheme))
urlOrUri.replaceFirst(scheme,"");
if (urlOrUri.startsWith("/"))
urlOrUri.replaceFirst("/","");
if (urlOrUri.endsWith("/"))
urlOrUri.replaceLast("/","");
// Example 2:
urlOrUri.replaceFirst("^https://+", "");
urlOrUri.replaceFirst("^/+", "");
urlOrUri.replaceFirst("/+$", "");
Upvotes: 0
Views: 42
Reputation: 38441
What's wrong with "custom code"? Everything you write is custom code.
Instead of repeating
if (urlOrUri.startsWith(scheme))
urlOrUri.replaceFirst(scheme,"");
write a method. And if you use .substring
instead of replaceFirst
there won't be any "rematching":
public String removePrefix(String input, String prefix) {
if (input.startsWith(prefix)) {
return input.substring(prefix.length());
}
return input;
}
Also the there is not much to learn about regexps the way you are using them here, except the regexps you are using don't do the same as example 1:
removePrefix("//example", "/"); // Returns "/example"
"//example".replace("^/+", ""); // Returns "example"
Even if you use the regexp, you should also write a method, that does this, instead of writing each regexp separately:
public String removePrefix(String input, String prefix) {
return input.replace("^" + Pattern.quote(prefix), "");
}
One more point: Since you are working with URLs/URIs, maybe you could use a URL parser library, but that depends on why you are doing this and what you actually are thing to achieve.
Upvotes: 0