-2

I am trying to check if a chosen path is a valid path for my Java program. In order to be valid, it must match the path E:\test\(someFolderName)\. The chosen folder can be deeper in that directory.

This is what I have tried:

String a = "E:\\test\\anotherFolder";
if (a.matches("E:\\\\btest\\b\\.*")) {
    System.out.println("match");
}

I have also tried putting test into [] but it did not work.

\b would mark the beginning of a word boundary, and adding \b again should close it, correct?

.* would match any character 1 to infinite times.

So, is there a problem with the escaping? Or do I need to group it differently?

VLAZ
  • 26,331
  • 9
  • 49
  • 67
Dahlin
  • 157
  • 1
  • 11
  • 3
    Not really the way to do it. You should really be using something like ```java.nio.file.Path.getParent()``` – g00se Oct 27 '22 at 18:13
  • 2
    Possibly related: [Java: How to check if a directory is inside other directory](https://stackoverflow.com/q/26518033) – Pshemo Oct 27 '22 at 18:17
  • This pattern will match whatever the last folder in the path is: "E:(?:\\\w+)*\\(.*)\\", see [here](https://regex101.com/r/17YEl7/1) for examples. As has been said, though, there are probably better was to deal with this. – JRiggles Oct 27 '22 at 18:18
  • I don't know, why this questions was closed again :-( So here's only a few things via comments :-/ Your `.` is escaped, so it matches stricly only a `.`, not . Then, `.*` (not escacped dot) _would_ match 0..* times, not 1..* times.. You should not use word boundary `\b` after `test`, because it doesn't make sense. If you want a backslash, match a backslash. Matching a backslash requires 4 backslashes (that's `\\\\ `.). The other comments are very valid: You should use `getParent()`. "test" in `[]` doesn't make sense, read the docs. – steffen Oct 27 '22 at 18:45
  • yeah exactly, people are so ignorant "yeah that thing was definitely answered somewhere else" Bruh, its not only about the backslashes here. Thanks for your answer! : 3 – Dahlin Oct 27 '22 at 18:49

1 Answers1

-1

Possible duplicated of escaping-special-characters-in-java-regular-expressions.

You need more backslashes. "The 4 slashes in the Java string turn into 2 slashes in the regex pattern. 2 backslashes in a regex pattern matches the backslash itself.".

tecop
  • 11
  • 5