Question

I'm trying to write a regex that matches the {QUERY_STRING} condition type.

Sample Data:

slug=something1 &slug=something2 &slug=something3 &slug=something4 &id=5645

Note: I've added the spaces for easier reading.

Regex so far:

^(slug=(\w+)|&slug=(\w+)|&id=(\d+))+

With this I'm able to access 5 callbacks:

  • {C:0} slug=something1 &slug=something2 &slug=something3 &slug=something4 &id=5645
  • {C:1} &id=5645
  • {C:2} empty
  • {C:3} empty
  • {C:4} 5645

What I'm trying to achieve:

  • {C:0} slug=something1 &slug=something2 &slug=something3 &slug=something4 &id=5645
  • {C:1} something1
  • {C:2} something2
  • {C:3} something3
  • {C:4} something4
  • {C:5} 5645

One other requirement:

I'm always passing the id as the last variable, and I'd like it to be in the 5th position all the time regardless of how many slugs are passed (to a maximum of 4, minimum of 1). Is this even possible?

Thank you!

Was it helpful?

Solution

Try

(?:slug=([a-zA-Z0-9]+)&)?(?:slug=([a-zA-Z0-9]+)&)?(?:slug=([a-zA-Z0-9]+)&)?(?:slug=([a-zA-Z0-9]+))?id=(\d+)+

Repeating the pattern is somewhat ugly, but I'm just not smart enough to find another expression.

The ?: in

(?:slug=([a-zA-Z0-9]+)&)

tells the processor not to capture the match.

This also achieves what you were asking for: the ID is always in C:5.

I tried this in my IIS 7.5 and it works, except if there is just one slug - in that case, this slug is captured into C:3. I have no idea why. Other regex testers (like http://regex101.com/#pcre) capture correctly.

I'll think about it, but if this takes too long or I don't come up with a solution, you can always add multiple rewrite rules (in this case, add an extra rule for one slug).

This is how it looks in IIS:

enter image description here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top