簡體   English   中英

python匹配正則表達式

[英]python match regular expression

我需要將一個主題與一個正則表達式進行比較,並將出現的內容與一個巧合的按鍵蒙版進行鏈接

key_mask = 'foo/{one}/bar/{two}/hello/{world}'

regex_mask = 'foo/(.*)/bar/(.*)/hello/(.*)'

subject = 'foo/test/bar/something/xxx'

返回應該是:

{
"one": "test",
"two": "something",
"world": "xxx"
}

用3個輸入實現此結果的最佳方法是什么?

(這是用於簡單的url路由過濾,例如symfony http://symfony.com/doc/current/book/routing.html

謝謝!

想到的最簡單的事情是在正則表達式中使用命名組:

>>> regex_mask = 'foo/(?P<one>.*)/bar/(?P<two>.*)/hello/(?P<world>.*)'
>>> subject = 'foo/test/bar/something/hello/xxx'
>>> re.match(regex_mask, subject).groupdict()
{'world': 'xxx', 'two': 'something', 'one': 'test'}

最簡單的方法是使用命名組,即使用(?P<name>.*)而不是普通(.*) (?P<name>.*) ,然后使用Match對象的groupdict()方法。

但是,如果您無法更改問題的輸入(因為您是從另一個庫中獲取它們或出於其他任何原因,則可以使用re.sub並使用一個簡單的函數如replkey_mask自動創建一個命名組正則表達式:

import re

def to_named_group(match):
    return '(?P<{}>.*)'.format(re.escape(match.group(0)[1:-1]))

def make_regex(key_mask):
    return re.compile(re.sub(r'\{[^}]+\}', to_named_group, key_mask))

def find_matches(key_mask, text):
    return make_regex(key_mask).match(text).groupdict()

用作:

In [10]: find_matches('foo/{one}/bar/{two}/hello/{world}', 'foo/test/bar/something/hello/xxx')
Out[10]: {'one': 'test', 'two': 'something', 'world': 'xxx'}

根據您的評論進行更新:

將有關正則表達式的更多信息傳遞給to_named_group很容易。 例如,您可以將代碼更改為:

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

這樣,您可以控制每個命名組應匹配的內容。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM