正则表达式 - 匹配除正斜杠以外的所有内容 [英] Regex - match everything but forward slash

查看:51
本文介绍了正则表达式 - 匹配除正斜杠以外的所有内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下字符串中:

/西雅图/餐厅

我想匹配西雅图(如果存在)(有时网址可能是/seattle/restaurant,有时可能是/restaurant).我不想要的是匹配以下正斜杠:seattle/

我尝试了以下方法,但无法正常工作:

/(.*[^/]?)restaurant(\?.*)?$

我需要第一个正斜杠,所以解决方案不是删除它,我可以这样做:

 (/?)(.*)/restaurant(\?.*)?$

谢谢

托马斯

解决方案

这样的事情怎么样?

^/([^/]+)/?(.*)$

我用 python 测试过,似乎工作正常:

<预><代码>>>>regex=re.compile(r'^/([^/]+)/?(.*)$')>>>regex.match('/seattle').groups()('西雅图', '')>>>regex.match('/seattle/restaurant').groups()(西雅图",餐厅")

in the following string:

/seattle/restaurant

I would like to match Seattle (if it is present) (sometimes the url might be /seattle/restaurant and sometimes it might be /restaurant). What I don't want is to match the following forward slash: seattle/

I have tried the following, but I cannot get it to work:

       /(.*[^/]?)restaurant(\?.*)?$

I need the first forward slash, so the solution is not to remove that, which I can do like this:

     (/?)(.*)/restaurant(\?.*)?$   

Thanks

Thomas

解决方案

What about something like this?

^/([^/]+)/?(.*)$

I tested it with python and seems to work fine:

>>> regex=re.compile(r'^/([^/]+)/?(.*)$')
>>> regex.match('/seattle').groups()
('seattle', '')
>>> regex.match('/seattle/restaurant').groups()
('seattle', 'restaurant')

这篇关于正则表达式 - 匹配除正斜杠以外的所有内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆