Author Topic: RegEx query  (Read 1996 times)

Dumah

  • Jackass IV
  • Posts: 960
  • Karma: +21/-6
RegEx query
« on: October 03, 2010, 05:20:43 PM »
I'm writing a quick regular expression in python to test an url path. I want it to look for a number of verbs and optionally pull out an integer:

Code: [Select]
pattern = r"/(?P<verb>view|edit|list|create|delete)(/(?P<id>\d{1,4})/)?"
paths = (
    "/view/1/",
    "/edit/15/",
    "/create/",
    "/list/",
    "/delete/2/",
    "/dummy/" #will not match
)

This pulls out the "verb" as well as an "id". Where there is no id it sets the group result to None. What I want is for the match to fail on paths that dont require an id (list, create) but to succeed on the others (view, edit,delete) and pull out the id.

Any ideas?

ober

  • Ashton Shagger
  • Ass Wipe
  • Posts: 14310
  • Karma: +73/-790
  • mini-ober is taking over
    • Windy Hill Web Solutions
Re: RegEx query
« Reply #1 on: October 03, 2010, 09:23:26 PM »
I pretty much suck at regex and I've spent about 30 minutes in my life with Python, so I'm afraid I won't be of much help.

Dumah

  • Jackass IV
  • Posts: 960
  • Karma: +21/-6
Re: RegEx query
« Reply #2 on: October 04, 2010, 01:31:03 AM »
No probs. I tried to use a negative lookback on the "id" section, but it seems that the python regex module will only apply a lookback if all the "verbs" I look back on are the same length.

For now I just added a bit of extra logic when the match is done....

Dumah

  • Jackass IV
  • Posts: 960
  • Karma: +21/-6
Re: RegEx query
« Reply #3 on: October 04, 2010, 05:40:11 AM »
Current version seems to work, but any pitfalls or optimisations would be appreciated

Code: [Select]
^/\b(?P<verb>(?:(?:view|edit|delete)(?=/(?P<id>\d{1,4})))|create|list)\b/?