I have implemented a very simple method:
private String getProfileName(String path) {
String testPath = null;
for (int i = 0; i < path.length(); i++) {
testPath = path.substring(0, i);
if ( testPath.endsWith("1") || testPath.endsWith("2") || testPath.endsWith("3") || testPath.endsWith("4") || testPath.endsWith("5") || testPath.endsWith("6") || testPath.endsWith("7") || testPath.endsWith("8") || testPath.endsWith("9") ) {
break;
}
}
return testPath.substring(0, (testPath.length() - 1));
}
I don’t like the whole method because I think it’s more complicated than necessary, especially the if condition.
So I thought of a way to refactor this method. First I thought of using Regex to replace the if condition, but isn’t regex a little bit too much for this simple case?
Any other ideas how to reafctor this?
Use this pattern with a matcher:
Example code:
I think this is much easier to understand than your code. It took me several minutes to work out your logic, and I had to run it to be sure. I think that with a regular expression it is quite clear what the code is doing. If you wish you can compile the regular expression just once and reuse it by moving it to a static member of the class.
Regular expressions have quite a bad stigma on Stack Overflow (mostly from people trying to use them to parse HTML, email addresses, URLs, and all sorts of other nasty inappropriate uses of regular expressions). But for this sort of task a regular expression is just fine.
You may also wish to consider why you are omitting 0 and if that is a good idea.