0

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

1
  • You can try [^\\]+\\[^\\]+$ Commented Mar 24, 2020 at 16:31

2 Answers 2

0

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

Sign up to request clarification or add additional context in comments.

Comments

0
[^\\]+\\[^\\]+$
  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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.