Eugene Mala
Eugene Mala

Reputation: 1273

Javascript: Check string to match pattern

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?

Upvotes: 1

Views: 538

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074138

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.

Upvotes: 4

Related Questions