查找 ///的正则表达式?

发布于 2024-12-06 04:53:15 字数 2165 浏览 2 评论 0原文

这是发布给我的

<*@google.com>写道:

<块引用>

嗨,尼克拉斯, 如果您只想映射此:/region/city/category/ 假设 它唯一的 此有效字符:[a-zA-Z0-9_] 您可以执行以下操作: - main.py

应用= webapp.WSGIApplication([('/([-\w]+)/([-\w]+)/([-\w]+)', 处理程序)],debug=True)

在你的处理程序上: 处理程序类(webapp.RequestHandler): def get(自身、地区、城市、类别): # 在方法中使用这些变量 希望这有帮助!

我的 web 应用程序应该处理 URI,例如 // 以及可选的城市和类别,例如

/rio_de_janeiro/grande_rio_de_janeiro/casas? #<region>/<city>/<category>
/gujarat/ahmedabad/vehicles-for_sale #<region>/<city>/<category>
/rio_de_janeiro/grande_rio_de_janeiro/ #<region>/<city>
/delhi #<region>

Etc 现在我想启用一个请求处理程序,它可以采用可选参数划分由分隔符 / 组成。如果我在请求处理程序中使用正则表达式 '/(.*) 和变量,第一个变量将变为 a/b,第二个变量将变为 b > 所以这几乎就是我想要的,但是 a 和 b 作为 2 个不同的变量。我为请求处理程序尝试的正则表达式是

application = webapp.WSGIApplication([('/(.*)',MyPage),

我的请求处理程序的功能头是

class MyPage(RequestHandler):
    def get(self, location='frankfurt', category='electronics'):

启用 HTTP 查询,例如/frankfurt、/frankfurt/、/frankfurt/ electronics、/madrid/apartments、/newyork 等允许所有可能的组合,您能给我一个可以实现我想要的功能的正则表达式吗? mod_rewrite 但对于 GAE。

澄清

这只是一个“使目录成为变量”的问题,因此这里有一些示例来澄清它应该如何表现

“/法兰克福”,-将“法兰克福”放入变量 1 '/frankfurt/', - 将 'frankfurt' 放入变量 1 '/frankfurt/Electronics', - 将 'frankfurt' 放入变量 1,将 'Electronics' 放入 virable 2 '/法兰克福/电子/',同上 '/eu/frankfurt/ electronics',与上面相同,即仅计算最后 2 组 '/eu/frankfurt/ electronics/',同上 “toronto/lightnings”,不以 / 开头,所以不起作用 '多伦多/闪电/',如上所述 '利马/汽车/旧',如上所述 'lima/cars/old/' 如上所述

我想要处理的典型情况是 /region/city/category 即如果我将示例应用于巴西它可能是 /rio_de_janeiro/grande_rio_de_janeiro/casas?对于 /region/city/category 或印度,可能是 /delhi/delhi/for_sale 或 /gujarat/ahmedab​​ad/vehicles-for_sale

解决方案

据我所知,答案中的解决方案适用于我的用途:

/(?:[^/]+)/?([^/]*)/?([^/]*)

This was posted to me

<*@google.com> wrote:

Hi Niklas,
If you just want to map this: /region/city/category/ supposing
its only
this valid characters: [a-zA-Z0-9_]
you can do the following:
- main.py

application =
webapp.WSGIApplication([('/([-\w]+)/([-\w]+)/([-\w]+)',
handler)],debug=True)

and on your handler:
class Handler(webapp.RequestHandler):
def get(self, region, city, category):
# Use those variables on the method
Hope this helps!

My webapp is suppossed to handle URI like <region>/<city>/<category> with optional city and category e.g.

/rio_de_janeiro/grande_rio_de_janeiro/casas? #<region>/<city>/<category>
/gujarat/ahmedabad/vehicles-for_sale #<region>/<city>/<category>
/rio_de_janeiro/grande_rio_de_janeiro/ #<region>/<city>
/delhi #<region>

Etc Now I want to enable a request handler that can take optional arguments divided by the separator /. If I use the regex '/(.*) and variables in the request handler the first varible becomes a/b and the second variable becomes b so that is nearly what I want but a and b as 2 different variables instead. The regex I tried for the request handler is

application = webapp.WSGIApplication([('/(.*)',MyPage),

And the function head of my request handler is

class MyPage(RequestHandler):
    def get(self, location='frankfurt', category='electronics'):

To enable an HTTP query e.g. /frankfurt, /frankfurt/, /frankfurt/electronics, /madrid/apartments, /newyork, etc allowing all possible combinations. Can you advice me a regex that can achieve what I want? I want functionality like a mod_rewrite but for GAE.

Thanks

Clarification

It's just a question of "make the directory a variable" so to clarify here are some examples how it should behave

'/frankfurt', - put 'frankfurt' in variable 1
'/frankfurt/', - put 'frankfurt' in variable 1
'/frankfurt/electronics', - put 'frankfurt' in variable 1 and 'electronics' in virable 2
'/frankfurt/electronics/', same as above
'/eu/frankfurt/electronics', same as above i.e. only last 2 groups count
'/eu/frankfurt/electronics/', same as above
'toronto/lightnings', doesn't start with / so shan't work
'toronto/lightnings/', as above
'lima/cars/old', as above
'lima/cars/old/' as above

Typical cases I want to handle is /region/city/category i.e. if I apply the example to Brazil it could be /rio_de_janeiro/grande_rio_de_janeiro/casas? for /region/city/category or for India it could be /delhi/delhi/for_sale or /gujarat/ahmedabad/vehicles-for_sale

Solution

As far as I can tell the solution from the answer works for my purposes:

/(?:[^/]+)/?([^/]*)/?([^/]*)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

蘸点软妹酱 2024-12-13 04:53:15

在您提供更多详细信息后,我现在可以提出另一种正则表达式模式:

import re

reg = re.compile('(?:/[^/]+(?=/[^/]+/[^/]+/?\Z)' # this partial RE matches the
                                                 # first of 3 groups, if 3
                 '|'    # OR
                 ')'   # nothing is catched
                 '/([^/]+)'  # the group always catching something
                 '(?:/([^/]+)?)?'  # the possible second or third group
                 '/?\Z' ) # the end

for ss in ('/frankfurt', '/frankfurt/',
           '/frankfurt/electronics', '/frankfurt/electronics/',
           '/eu/frankfurt/electronics', '/eu/frankfurt/electronics/',
           'toronto/lightnings', 'toronto/lightnings/',
           'lima/cars/old', 'lima/cars/old/',
           '/rio_de_janeiro/grande_rio_de_janeiro/casas/Magdalena'):
    mat = reg.match(ss)
    print ss,'\n',mat.groups() if mat else '- No matching -','\n'

结果

/frankfurt 
('frankfurt', '') 
/frankfurt/ 
('frankfurt', '') 
/frankfurt/electronics 
('frankfurt', 'electronics') 
/eu/frankfurt/electronics/ 
('frankfurt', 'electronics') 
toronto/lightnings 
- No matching - 
lima/cars/old/ 
- No matching -
/rio_de_janeiro/grande_rio_de_janeiro/casas/Magdalena 
- No matching -

但是,您知道,使用正则表达式并不是解决您的问题绝对必要的:

for ss in ('/frankfurt', '/frankfurt/',
           '/frankfurt/electronics', '/frankfurt/electronics/',
           '/eu/frankfurt/electronics', '/eu/frankfurt/electronics/',
           'toronto/lightnings', 'toronto/lightnings/',
           'lima/cars/old', 'lima/cars/old/',
           '/rio_de_janeiro/grande_rio_de_janeiro/casas/Magdalena'):
    if ss[0]=='/':
        splitted = ss.rstrip('/').split('/')
        if len(splitted)==2:
            grps = splitted[::-1]
        elif len(splitted) in (3,4):
            grps = splitted[-2:]
        else:
            grps = None
    else:
        grps = None
    print ss,'\n',grps if grps else '- Incorrect string -','\n'

结果与上面相同。

After you have given more details, I can now propose another regex pattern:

import re

reg = re.compile('(?:/[^/]+(?=/[^/]+/[^/]+/?\Z)' # this partial RE matches the
                                                 # first of 3 groups, if 3
                 '|'    # OR
                 ')'   # nothing is catched
                 '/([^/]+)'  # the group always catching something
                 '(?:/([^/]+)?)?'  # the possible second or third group
                 '/?\Z' ) # the end

for ss in ('/frankfurt', '/frankfurt/',
           '/frankfurt/electronics', '/frankfurt/electronics/',
           '/eu/frankfurt/electronics', '/eu/frankfurt/electronics/',
           'toronto/lightnings', 'toronto/lightnings/',
           'lima/cars/old', 'lima/cars/old/',
           '/rio_de_janeiro/grande_rio_de_janeiro/casas/Magdalena'):
    mat = reg.match(ss)
    print ss,'\n',mat.groups() if mat else '- No matching -','\n'

result

/frankfurt 
('frankfurt', '') 
/frankfurt/ 
('frankfurt', '') 
/frankfurt/electronics 
('frankfurt', 'electronics') 
/eu/frankfurt/electronics/ 
('frankfurt', 'electronics') 
toronto/lightnings 
- No matching - 
lima/cars/old/ 
- No matching -
/rio_de_janeiro/grande_rio_de_janeiro/casas/Magdalena 
- No matching -

But, you know, using a regex isn't absolutely necessary to solve your problem:

for ss in ('/frankfurt', '/frankfurt/',
           '/frankfurt/electronics', '/frankfurt/electronics/',
           '/eu/frankfurt/electronics', '/eu/frankfurt/electronics/',
           'toronto/lightnings', 'toronto/lightnings/',
           'lima/cars/old', 'lima/cars/old/',
           '/rio_de_janeiro/grande_rio_de_janeiro/casas/Magdalena'):
    if ss[0]=='/':
        splitted = ss.rstrip('/').split('/')
        if len(splitted)==2:
            grps = splitted[::-1]
        elif len(splitted) in (3,4):
            grps = splitted[-2:]
        else:
            grps = None
    else:
        grps = None
    print ss,'\n',grps if grps else '- Incorrect string -','\n'

The results are the same as above.

聽兲甴掵 2024-12-13 04:53:15

您可以尝试

/(?:[^/]+)/?([^/]*)/?([^/]*)

将“a/b”放入变量 1,将“a”放入变量 2,将“b”放入变量 3。不确定这是否是您想要的。

You can try

/(?:[^/]+)/?([^/]*)/?([^/]*)

which will put 'a/b' in variable 1, 'a' in variable 2 and 'b' in variable 3. Not sure if that is what you want.

淡墨 2024-12-13 04:53:15

一个可能适合您的解决方案,尽管您可能会发现它太硬编码:

您的应用程序的路由结构如下:

routes = [
    ('/foo/([a-zA-Z]+)/?', TestHandler),
    ('/foo/([a-zA-Z]+)/([a-zA-Z]+)/?', TestHandler),
    ('/foo/([a-zA-Z]+)/([a-zA-Z]+)/([a-zA-Z]+)/?', TestHandler)
]

在您的处理程序中,您将检查len(args),如下所示:

class TestHandler(webapp.RequestHandler):
    def get(self, *args):
        if len(args): # assign defaults, perhaps?

A solution that may work for you, though you may find it too hardcoded:

Routes for your app structured like this:

routes = [
    ('/foo/([a-zA-Z]+)/?', TestHandler),
    ('/foo/([a-zA-Z]+)/([a-zA-Z]+)/?', TestHandler),
    ('/foo/([a-zA-Z]+)/([a-zA-Z]+)/([a-zA-Z]+)/?', TestHandler)
]

And in your handler you'd check len(args), something like:

class TestHandler(webapp.RequestHandler):
    def get(self, *args):
        if len(args): # assign defaults, perhaps?
盛夏尉蓝 2024-12-13 04:53:15

如果你只想映射这个:(地区)/(城市)/(类别)/假设它只有这个有效字符:[a-zA-Z0-9_]

你可以执行以下操作:
- main.py

application = webapp.WSGIApplication([
                    ('/([-\w]+)/([-\w]+)/([-\w]+)', Handler)
],debug=True)

和你的处理程序:

class Handler(webapp.RequestHandler):
    def get(self, region, city, category):
        # Use those variables on the method

希望这有帮助!

If you just want to map this: (region)/(city)/(category)/ supposing its only this valid characters: [a-zA-Z0-9_]

you can do the following:
- main.py

application = webapp.WSGIApplication([
                    ('/([-\w]+)/([-\w]+)/([-\w]+)', Handler)
],debug=True)

and on your handler:

class Handler(webapp.RequestHandler):
    def get(self, region, city, category):
        # Use those variables on the method

Hope this helps!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文