Search code examples
regexmod-rewritelookbehind

Mod Rewrite RegEx To Match Only If Previous Subset Matched


I am trying to make what I think is a simple regex for use with mod_rewrite.

I've tried various expressions, many of which I thought were promising, but all of which ultimately failed for one reason or another. They all also seem to fail once I add start/end string delimiters.

For example, ^user/(\d{1,10})(?=/)$ was one I tried, but among other things, it seems to group the trailing slash, and I only want to group the digits. I think I need to use a positive lookbehind, but I'm having difficulty because it's looking behind at a group.

What I am trying to match is strings that 1) begin with "user/" and 2) possibly end with (\d{1,10})/ (1 to 10 digits followed by a single slash)

Should Match:

user/
user/123/
user/1234567890/

Should not match:

user
user//
user/-4/
user/35.5/
user/123
user/123//
user/123/5/
user/12345678901/

Edit: Sorry about the formatting; I do not understand how to format anything via this markdown. Those examples are preceded by 4 spaces which I thought should make a code block, but obviously I thought wrong.


Solution

  • ^user/(?:([0-9]{1,10})/)?$ should work just fine.