2

How can I simplify my regexp (^(\w+)\/(\w+)\/(\d+)$|^(\w+)\/(\w+)\/$|^(\w+)\/(\w+)$) to match examples like controller/action(/id)? My current regex looks so long and complex :(

Matching examples:

controller/action
controller/action/
controller/action/123

Non-matching:

controller/
controller/action/action
controller/action/123/
controller/action/123/456
3
  • Does Non-matching: mean you do not want to match them? Commented Feb 15, 2016 at 21:36
  • Will they all start controller/action? Commented Feb 15, 2016 at 21:37
  • @WiktorStribiżew yes, sorry Commented Feb 15, 2016 at 21:38

1 Answer 1

4

You can use the following regex featuring optional groups:

^(\w+)\/(\w+)(?:\/(\d+)?)?$
             ^^^       ^ ^

See the regex demo

This regex matches:

  • ^ - start of a string
  • (\w+) - one or more alphanumeric or underscore characters
  • \/ - a / symbol
  • (\w+) - one or more alphanumeric or underscore characters
  • (?:\/(\d+)?)? - an optional (one or zero occurrences) sequence (due to (?:...)? construct, a non-capturing group (?:...) + a ? - one or zero - quantifier) matching
    • \/ - a forward slash
    • (\d+)? - optional capturing group matching one or more digits (but this group can be missing since the ? quantifier is applied to the whole group (...))
  • $ - end of string anchor.
Sign up to request clarification or add additional context in comments.

3 Comments

Just a smidge faster than I was!
@Trasiva: I hope you were also going to write the explanation like mine. If you are, I can delete my answer.
@WiktorStribiżew I was, but you got there first (I already nuked my answer). To the victor go the spoils.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.