1

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?

asked Mar 23, 2016 at 15:17
2
  • In your example 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 ? Commented Mar 23, 2016 at 15:22
  • try using indexOf method var str = "Hello world, welcome to the universe."; var n = str.indexOf("welcome"); w3schools.com/jsref/jsref_indexof.asp Commented Mar 23, 2016 at 15:28

1 Answer 1

4

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 backslash
  • 1円 - 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

On regex101

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.

answered Mar 23, 2016 at 15:23
Sign up to request clarification or add additional context in comments.

2 Comments

I thinky you should add the dot to the last negated character class, otherwise it would match e.g. \folder\folder.test.jpg
@SebastianProske: You're right, I've fixed it. Although I suppose it depends on your definition of "extension" (is the extension .jpg or .test.jpg). I agree with yours, though.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.