user3925023
user3925023

Reputation: 687

Regex - count number of characters to validate match

My goal is to validate instagram profile links via a regular expression. So for example this one is valid: https://www.instagram.com/test.profile/

This one is not: https://www.instagram.com/explore/tags/test/

Using this regex

(?:(?:http|https):\/\/)?(?:www\.)?(?:instagram\.com|instagr\.am)\/([A-Za-z0-9-_\.]+)

On this text: https://www.instagram.com/explore/tags/test/ produces a match https://www.instagram.com/explore, but this one I want to avoid and discharge. LIVE DEMO HERE

My question: is possible to add an additional syntax in the regex to validate a match ONLY if the string contains exactly 4 slashes (/)?

Upvotes: 1

Views: 125

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627488

You can make the / char obligatory if you add \/ at the end:

^(?:https?:\/\/)?(?:www\.)?(?:instagram\.com|instagr\.am)\/([\w.-]+)\/$

Note that [a-zA-Z0-9_] can most probably be replaced with \w (especially, if it is JavaScript, PHP, Java or Ruby) to make the pattern shorter. It won't hurt even in those regex flavors where \w is Unicode-aware by default (Python re, .NET).

See the regex demo. Details:

  • ^ - start of string
  • (?:https?:\/\/)? - an optional http:// or https://
  • (?:www\.)? - an optional www. string
  • (?:instagram\.com|instagr\.am) - instagram.com or instagr.am
  • \/ - a / char
  • ([\w.-]+)- Group 1: one or more letters, digits, _, . or - chars
  • \/ - a / char
  • $ - end of string.

Upvotes: 1

Related Questions