Akira Kotsugai
Akira Kotsugai

Reputation: 1159

how to write a regex to match characters separated by 3 slashes?

any string could be inside amongst the slashes, but there must be only 3 divisions. For instance, Values that should match:

  1. "90/90/90/9090"
  2. "FDSAFDSA/90/pppppaA3/9090"

Values that should not match:

  1. "90/90/90/9090/90"
  2. "FDSAFDSA/90/pppppaA3/9090/90"

I am using python and the re library, I have tried lots of combination but none of them worked:

 bool(re.match(r'^.*\/.*\/.*\/((?!\/).)*$', "90/90/90/9090/90"))
 bool(re.match(r'^.*\/.*\/.*\/((?!/).)*$', "90/90/90/9090/90"))
 bool(re.match(r'^.*\/.*\/.*\/(?!(/)$).*$', "90/90/90/9090/90"))
 bool(re.match(r'^.*\/.*\/.*\/(/).*$', "90/90/90/90/90"))
 bool(re.match(r'^.*\/.*\/.*\/.*(\/)$', "90/90/90/90/90"))

Upvotes: 1

Views: 234

Answers (1)

Aaron
Aaron

Reputation: 24802

You ought to use negated character classes :

^[^/]*/[^/]*/[^/]*/[^/]*$

[^/] matches any character but /, so we represent a string that contains three / and anything else around them.

In your regexes, the . could match anything including /, and while you could have approximated an equivalent of negated character classes using negative lookarounds, you didn't properly apply them to every . you had : ^((?!\/).)*\/((?!\/).)*\/((?!\/).)*\/((?!\/).)*$ would have worked too, although it would have been less performant.

And there's no need to escape those /, they aren't regex meta-characters. You might need to escape them in languages or tools that use / as delimiters, such as JavaScript's /pattern/ syntax or sed's s/search/replace/ substitutions.

Upvotes: 5

Related Questions