Home > front end >  Regex need to grab file name along with directory file is stored in
Regex need to grab file name along with directory file is stored in

Time:12-16

I believe the regex expression I need would work in any language but I will be using it for VB.Net. I need it get grab the file name along with the directory it is in. I only need it to capture "TEST-couldbe1\FINAL-word.txt" from "A:\TEST2-maybe1\TEST-couldbe1\FINAL-word.txt". All the things I have tried captures everything up to the colon or just the filename with the \ . Best code I have is below, Thanks for your help.

\\(?:.(?!\\)) $

CodePudding user response:

I wouldn't use regex at all. The System.IO namespace has all the required functionality. The following code does what you need:

Dim fullpath As String = "A:\TEST2-maybe1\TEST-couldbe1\FINAL-word.txt"

Dim fileName As String = IO.Path.GetFileName(fullpath)
Dim fullDir As String = IO.Path.GetDirectoryName(fullpath)
Dim fullParentDir As String = IO.Path.GetDirectoryName(fullDir)

Dim finalStr As String = $"{fullDir.Substring(fullParentDir.Length   1)}{IO.Path.DirectorySeparatorChar}{fileName}"

CodePudding user response:

Can you try this?

\w\\([.\w\\-] )

Input

A:\TEST2-maybe1\TEST-couldbe1\FINAL-word.txt

Output

enter image description here

Try at https://regex101.com/r/rwy8o6/1

CodePudding user response:

The pattern \\(?:.(?!\\)) $ that you tried matches \ and then 1 times any character except \

This way it does not match what comes before the leading \ so you can add matching that using a negated character class:

[^\\] \\(?:.(?!\\)) $

But this pattern contains a part that is called a tempered greedy token (?:.(?!\\)) which makes it costly on performance and can be written using a negated character class:

[^\\] \\[^\\] $

Regex demo

Or more specific with a dot in the filename:

[^\\] \\[^\\] \.[^\\.] $

Regex demo

  • Related