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

Testing for exact string with Regexp

I’m trying to find the exact match for the following strings;

/test/anyAlphaNumericId123
/test/anyAlphaNumericId123/

That will not match the following

/test/anyAlphaNumericId123/x

I have the following Regex currently, which matches both former cases and not the latter;

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

/(\/test\/)(.*?)(\/|$)/

But on attempting to call str.match on it, I will also get a result for the latter, as it has a partial match. Can I accomplish this with Regex alone?

>Solution :

You can write the pattern as:

^\/test\/[a-zA-Z0-9]+\/?$

The pattern matches:

  • ^ Start of string
  • \/test\/ Match /test/
  • [a-zA-Z0-9]+ Match 1+ times any of the allowed ranges
  • \/? Match an optional /
  • $ End of string

Regex demo

Example using a case insensitive match with the /i flag:

const regex = /^\/test\/[a-z0-9]+\/?$/i;
[
  "/test/anyAlphaNumericId123",
  "/test/anyAlphaNumericId123/",
  "/test/anyAlphaNumericId123/x"
].forEach(s =>
  console.log(regex.test(s) ? `Match: ${s}` : `No match ${s}`)
);
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