Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

125
Views
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

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.

about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

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\/|$)
about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!