简体   繁体   中英

Regex to get last directory and filename from a path

So, I have an example path c:\\folder1\\folder2\\folder3\\file.txt I want regex to pull folder3\\file.txt

I figured this would be everything after

1. a slash
2. followed by any number of non slash characters
3. followed by a slash
4. followed by any number of non slash characters
5. followed by a dot 
5.1 that is not (eventually) followed by a slash

I've got most of it working

\\(?=[^\\]*(?=\\(?=[^\\]*(?=[\.]))))(.*)

unless I do this:

c:\\folder1\\folder2\\fol.der3\\file.txt (fol.der3 is the name of the directory)

or this

c:\\folder1\\folder2\\folder3\\file.txt\\ (technically there is no file here)

So, I've got everything except step 5.1

So, I tried adding a negative lookahead after my dot seeking lookahead so it would exclude dots that have a slash somewhere after them:

(?=[\.][^\\]*(?![\\]))

but that didnt work

Any ideas?

Thanks Chris

You could use a capturing group instead of using the lookaround and while still making use of the negative character classes .

\\([^\\]+\\[^\\.]+\.[^\\.]+)$

Explanation

  • \\\\ Match \\
  • ( Capture group 1
    • [^\\\\]+\\\\ Match 1+ occurrences of any char except \\ and then match \\
    • [^\\\\.]+\\. Match 1+ occurrences of any char except \\ or . and then match \\
    • [^\\\\.]+ Match 1+ occurrences of any char except \\ or .
  • ) Close group 1
  • $ End of string

Regex demo

[^\\]+\\[^\\]+$
  1. [^\\\\]+ - matches any character except \\ one or more times
  2. \\\\ - matches a single \\
  3. [^\\\\]+ - matches any character except \\ one or more times
  4. $ - matches the end of string

This is enough to get the last two pieces of your URI.

Whether the last piece is a folder or a file really can't be determined with regex as

  • files are not required to have an extension
  • URI of a folder does not end with a slash

Unless you can be sure of your input and that proves one of these two points invalid then the regex should be modified accordingly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM