I have the path ../dir1/dir2/dir3/filename.txt
and want to extract just filename
between the final and
.
using regex. The file extension will also not always be .txt
.
Currently I am doing (?<=/).+(?=.)
but selects from the first , including the directory names. I would love this to just be match-based and not using groups. Oh and using ECMA regex if that’s important.
2
Answers
You can use the below regex to achieve your purpose:
Explanation of the above regex:
([w-]+)
– Capturing group that matches one or more (+) word characters (w) or hyphens (-). Usually filenames containsw
characters so I used that but if it contains other special characters feel free to amend it as per your need..
– matches a literal dot character..*
– matches any character (.) zero or more times (*).$
– matches end of line. So basically the full regex matches any string that contains a word (consisting of one or more word characters or hyphens) followed by a dot and any characters until the end of the line. The word before the dot is captured for later use and this capturing group gives you your desiredfilename
.REGEX DEMO
Alternative Way:(Using Javascript functions)
If you match the regular expression
either:
Demo
We can break this expression down as follows.
You may also wish to hover (the cursor, not your person) over different parts of the expression at the link to obtain explanations of their functions.