1

I have a router module, what compares a subject with a regex, and link the occurrences with a coincident key mask. (its a simple url routing filtering like symfony http://symfony.com/doc/current/book/routing.html)

import re
from functools import partial

def to_named_groups(match, regexes):
    group_name = re.escape(match.group(0)[1:-1])
    group_regex = regexes.get(group_name, '.*')
    return '(?P<{}>{})'.format(group_name, group_regex)

def make_regex(key_mask, regexes):
    regex = re.sub(r'\{[^}]+\}', partial(to_named_groups, regexes=regexes),
                   key_mask)
    return re.compile(regex)

def find_matches(key_mask, text, regexes=None):
    if regexes is None:
        regexes = {}
    try:
        return make_regex(key_mask, regexes).search(text).groupdict()
    except AttributeError:
        return None

.


find_matches('foo/{one}/bar/{two}/hello/{world}', 'foo/test/bar/something/hello/xxx')

output:

{'one': 'test', 'two': 'something', 'world': 'xxx'} Blockquote


find_matches('hello/{city}/{phone}/world', 'hello/mycity/12345678/world', regexes={'phone': '\d+'})

output:

{'city': 'mycity', 'phone': '12345678'} Blockquote


find_matches('hello/{city}/{phone}/world', 'hello/something/mycity/12345678/world', regexes={'phone': '\d+'})

output:

{'city': 'something/mycity', 'phone': '12345678'}

This is mismatching (should return None and not the 'city': 'something/mycity'). How can i solve this? how can i match with the first "/" occurrence or another way?

Thanks!

2
  • Your code defines a find_matches that takes parameters key_mask, text, regexes. But you're calling it with a keyword argument requirements. Is that supposed to be regexes? Otherwise, it doesn't even run; it gets an immediate TypeError for invalid arguments.
    – abarnert
    Sep 17, 2013 at 22:17
  • yes, are regexes, sorry, edited :)
    – fj123x
    Sep 17, 2013 at 22:19

2 Answers 2

1

Let's look at the regex you're building:

hello/(?P<city>.*)/(?P<phone>\d+)/world

That .* will match anything, including something with slashes in it, as long as there are enough slashes left over to match the rest of the pattern.

If you don't want it to match slashes… you already know how to do that, because you're doing the exact same thing in the re.sub: use a character class of everything but slash, instead of a dot.

def to_named_groups(match, regexes):
    group_name = re.escape(match.group(0)[1:-1])
    group_regex = regexes.get(group_name, '[^/]*')
    return '(?P<{}>{})'.format(group_name, group_regex)

But meanwhile, if you don't understand the regexps you're building, why are you building them? You can parse this into path-separated components a lot more easily with just .split('/'). For example, without the extra regexes, I think this is what you're going for:

def find_matches(key_mask, text):
    mapping = {}
    for key, value in zip(key_mask.split('/'), text.split('/')):
        if key[0] == '{' and key[-1] == '}':
            mapping[key[1:-1]] = value
        elif key != value:
            return
    return mapping

And regexes is just a way to add some validation checks. (As written, it could be used to break the normal slash-separation scheme, but I think that's a bug, not a feature—in fact, I think it's exactly the bug that drove you to StackOverflow in the first place.) So, just do them explicitly:

def find_matches(key_mask, text, regexes={}):
    mapping = {}
    for key, value in zip(key_mask.split('/'), text.split('/')):
        if key[0] == '{' and key[-1] == '}':
            key=key[1:-1]
            if key in regexes and not re.match(regexes[key], value):
                return
            mapping[key] = value
        elif key != value:
            return
    return mapping

The second version already prevents the regexes from matching /, because you've split out the slashes before you even apply them. So, you don't need the sanitization you asked for in a comment.

But either way, the simplest way to sanitize your regexes is to sanitize them before you use them, rather than to use a regex to build everything into one big regex and then try to sanitize that. For example:

regexes = {key: regex.replace('.*', '[^/]*') for key, regex in regexes.items()}
2
  • i want to sanitize the regexes: .* -> [^/]*, etc
    – fj123x
    Sep 18, 2013 at 9:30
  • @fj123x: And? First, that doesn't seem to be part of your original question. Second, you don't need to do that if you're already splitting on / separately, as in my last example. And either way, the obvious way to do it is to sanitize each regex in regexes before you use them. I'll edit the answer to explain.
    – abarnert
    Sep 18, 2013 at 17:29
0

Consider changing group_regex to something a little more restrictive, such as [^/]* (to allow any non-slash character) or making it less greedy, such as .*?

Source: http://docs.python.org/2/library/re.html

1
  • Making it non-greedy wouldn't actually help here; that will make it prefer as few components as possible instead of as many as possible, but here we want to force it to only 1.
    – abarnert
    Sep 17, 2013 at 22:23

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.