3

Is it possible to check if a text is fully matched by a part of regular expression?

I'd like to match text that is a prefix of (potentially) matching text.

So, for example, I have a following regex:

/etc/tomcat/conf/.*

I'd like to match all files in directory /etc/tomcat/conf/. I can do that by matching full file name against my regex. But I need first to enter that directory, so I'd like to check if I need to enter /etc and /etc/tomcat in first line.

Is it possible to achieve in general case? The regex to match files will come from external system, so it's possible I'd get a regex in form:

/et..tomcat/con.* 

If I understand regex machines correctly, it should be possible, because the /et..tomcat/ would be matched agaist /etc/tomcat/, but the match will be negative because the text will and in that moment and the part con.* would not be satisfied. I'd need only to access the internal information, that the text was fully consumed but regex not...

Do Java provides means to check that?

9ilsdx 9rvj 0lo
  • 7,955
  • 10
  • 38
  • 77
  • Check the `Matcher`'s documentation: https://docs.oracle.com/javase/8/docs/api/java/util/regex/Matcher.html. The `hitEnd()` method is probably what you are looking for. – Vadim Landa Sep 06 '17 at 12:04
  • @VadimLanda thanks, I've made a quick test and it is exactly what I need – 9ilsdx 9rvj 0lo Sep 06 '17 at 12:16
  • @LucasTrzesniewski yes, the answer from that question is exactly what I need. The tricky part is, I haven't looked for 'partial mapping' because I'd thought of it only as a case where the whole regex matches a part of the text, not the opposite. – 9ilsdx 9rvj 0lo Sep 06 '17 at 12:16

1 Answers1

0

Only a overcomplex regex. As the idea is to go for single subdirectories, one could do:

Path full = Paths.get("/etc/tomcat/conf");

assert okay(full, Paths.get("/etc")); // -1-
assert !okay(full, Paths.get("/and/so/on")); // -2-

boolean okay(Path full, Path input) {
    try {
        input.relativize(full); // -1- "tomcat/conf"
        return true;
    } catch (IllegalArgumentException e) {
        return false; // -2-
    }
}

Though a bit more code without exception might be worth the effort.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138