Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Ensure regex test fails even if string matches an earlier portion of the pattern

Apologies if the title is too vague, I don’t know the terminology for this issue so any suggestions would be much appreciated!

Current pattern: ^(?:\/[^\/]*){2}(?:\/tree|)

Target language/platform: JS

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Inputs and expected results:

1. /foo/bar                                 pass
2. /foo/bar/tree/baz                        pass
3. /foo/bar/tree/baz/foobar                 pass

4. /foo/bar/blob                            fail
5. /foo/bar/blob/x.js                       fail

Testing mechanism: pattern.test(entryString);

These are GitHub paths, and what I’m trying to do is match a repository (/foo/bar), or any subpath (/foo/bar/tree/baz/....). The third path segment should be tree if it exists, else, the test should fail.

The problem with the pattern above is that the 4th & 5th items still pass despite matching neither condition of that pattern. It’s probably some silly mistake, but can’t figure out what it is.

>Solution :

You could optionally match /tree followed by optional repetitions or / and other chars than / and assert the end of the string $ to prevent partial matches.

^(?:\/[^\/]*){2}(?:\/tree(?:\/[^\/]*)*)?$

Explanation

  • ^ Start of string
  • (?:\/[^\/]*){2} Repeat 2 times / and optionally any char except /
  • (?: Non capture group
    • \/tree Match /tree
    • (?:\/[^\/]*)* Optionally repeat / any char except /
  • )? Close the non capture group and make it optional
  • $ End of string

Regex demo

If you don’t need to match the whole string, you can assert the end of the string in the alternation:

^(?:\/[^\/\n]*){2}(?:\/tree\/|$)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading