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

Time:07-15

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

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.

CodePudding user response:

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\/|$)
  • Related