I need to get a value from a file path.
assume my path looks like any other path:
c:\SomeFolder\SomeOtherfolder\A_Specific_Folder\what_i_want\another_folder\bla.txt
I can infer the name of ‘A_Specific_Folder’ at runtime, and i need to get ‘what_i_want’.
I know that ‘what_i_want’ is a number
I currenly use a regex like this:
public String getValueThatIneed(String path) {
String regex = String.format("%s\\\\([0-9]+)\\\\", varContainingNameOfSpecificFolder);
Pattern p = Pattern.compile(regex);
Matcher matcher = compile.matcher(path);
matcher.find(); \\because otherwise i can't use matcher.start()
String myValue = path.substring(matcher.start(1), matcher.end(1));
return myValue;
}
All this just to get this tinyValue from one String.
Now assume that i must have this in a method because I use it in 10 places.
But in one of the places I suddenly need to do some other operation on the stirng that would again require me to do all the patter, matcher stuff, with the same regex, just to get matcher.end(1), because maybe thats all i need over there.
Is there shorter way to do this?
thanks.
I see several minor problems in your code:
varContainingNameOfSpecificFoldercontains characters that have a meaning in regular expressions (.being the most likely candidate), then you must usePattern.quote()to quote that part.String.format()is unnecessary, you can use simplyStringconcatenation using+here, which is easier to read.myValue, simplyreturnthe result ofsubstringsubstringcall is unnecessary here! Simply replacing that expression withmatcher.group(1)has the same effect!String.replaceAll()might be a valid shortcut, but you’d have to modify your regex slightly.So my version would be:
If you don’t care about error checking (as your code doesn’t do it either) you can simply return the result of the
replaceAll()method and have a two-line method:However, I strongly encourage you to keep it, as otherwise you can easily miss nasty bugs in your code.