0
private static final String MY_MATCH = "(.+)/my_path/my_file[.](.+)";

The above is working as expected.

However, if my_path is determinable during run-time, does there exist a pre-existing method that "allows" static final? e.g. Maybe similar to Perl run-time code eval.

My solution(pseudo-code):

private static final String MY_MATCH = "(.+)/[unknown_path]/my_file[.](.+)";

static method (String my_path) {
//local var
String my_match = MY_MATCH;
my_match.replace("[unknown_path]", my_path));
Pattern my_pattern = Pattern.compile(my_match);
}

I feel uneasy with the string replace, but I do not see any other solution.

Grinnz
  • 9,093
  • 11
  • 18
PaulM
  • 345
  • 2
  • 11
  • Put some placeholder in `MY_MATCH` then replace it at runtime? Also, what does `design-patterns` have to do with this? – VLAZ Jan 23 '20 at 15:34
  • 1
    Does this answer your question? [Java generating Strings with placeholders](https://stackoverflow.com/questions/17364632/java-generating-strings-with-placeholders) – VLAZ Jan 23 '20 at 16:11
  • The StrSubstitutor looks promising! I dislike not being able to pre-compile the pattern into static final Pattern, vs static final String. That part is not possible, correct? – PaulM Jan 23 '20 at 16:57
  • Well, you can use a [static block to initialise a `static final` member](https://stackoverflow.com/a/2420405/3689450). So that will work once and it can be delayed until (essentially) the startup of the application. If that works, then it's a decent choice. However, if you need to wait until *after* the statup to fetch the value that goes in the placeholder, then a static block won't help. I suppose you can have a getter for the Pattern and once you know what it is, compute it and cache it, so repeat calls to the getter will just return the existing one. – VLAZ Jan 23 '20 at 17:09
  • 1
    This seems like a task better suited to methods which don’t use a regular expression at all. The first capture group can be obtained with `Paths.get(myPath).getParent().getParent()`. The second capture group can be obtained with `String filename = Paths.get(myPath).getFileName().toString(); String extension = filename.substring(filename.lastIndexOf('.') + 1);`. – VGR Jan 23 '20 at 19:03

0 Answers0