简体   繁体   中英

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\\ \\ .jpg \\ .jpg

Can this test be made in javascript using one regular expression?

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 (eg, 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM