Patrick Bard
Patrick Bard

Reputation: 1846

Regex to dynamically ignore some parts of a given path

Consider that I have the following string which is a "complete path":

/A/B/C/D/E    

And there is also the "simplified path" string:

/A/B/E

I have a situation where some parts of the string can be omitted and still be represent the full path. I know this is strange, but I can't change it.

Basically for this case, I need a regex to ignore the last two paths before the current path (dynamically as I have no specific information of them), to confirm that these two strings have a correlation.

The only thing I could came up with was:

But I think there must be a cleaner way to do this.

Upvotes: 0

Views: 310

Answers (2)

Yaron
Yaron

Reputation: 1242

I came up with the following solution:

  • Search string: [^\/]+\/[^\/]+\/([^\/]+$)

  • Replace string: \1

Check it here

Upvotes: 1

SomeJavaGuy
SomeJavaGuy

Reputation: 7347

If both path point to the same file/directory then you could make use of the Files class. It has a method Files#isSameFile to which you pass two Path instances and it would check if both files are pointing to the same file at your directory. This simple line would check if A/B/E/ and /A/B/C/D/E are actually the same directory.

System.out.println(Files.isSameFile(Paths.get("/A/B/C/D/E"), Paths.get("/A/B/E"))); 

Upvotes: 1

Related Questions