I need to test string weather it matches a specific pattern.
String is the full file path, for example:
C:\some\path\to\folder\folder.jpg
or
C:\another\file\path\file.jpg
Pattern is: file name without extension should match exact parent folder name, where it is located. File name could be any possible value.
So, in my example only first string matches pattern:
C:\some\path\to\folder\folder.jpg
Can this test be made in javascript using one regular expression?
1 Answer 1
Yes, you can, with a back reference:
\\([^\\]+)\\1円\.[^.\\]*$
The first group ([^\\]+)
captures the folder name, then the back reference (1円
) refers back to it saying "the same thing here."
So in the above, we have:
\\
- matches a literal backslash([^\\]+)
- the capture group for the folder name\\
- another literal backslash1円
- the back reference to the capture group saying "same thing here"\.
- a literal.
(to introduce the extension)[^.\\]*
- zero or more extension chars (you may want to change*
to+
to mean "one or more")$
- end of string
If you consider C:\some\path\to\folder\folder.test.jpg
a valid match (e.g., you think of the extension on folder.test.jpg
as being .test.jpg
, not .jpg
), just remove the .
from the [^.\\]
near the end.
If you want to allow for files without an extension, perhaps \\([^\\]+)\\1円(?:\.[^.\\]+)?$
. The (?:\.[^.\\]+)?
is the optional extension.
2 Comments
\folder\folder.test.jpg
.jpg
or .test.jpg
). I agree with yours, though.
folder.jpg
does have an extention of.jpg
. How is condition file name without extension should match exact parent folder name, where it is located satisfied here ?