Processing math: 100%
dps123456789 2018-05-28 01:47
浏览 81
已采纳

php regex最后有可选的char

i have the following string

https://www.example.com/int/de

and want to match the language code at the end of the url, eg 'de' i do that with this regex

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

I would also like to get the same result if the URL ends with a slash

But with https://www.example.com/int/de/ i only get a full match, but the group dont match 'de' anymore, although the last slash is optional in the regex

can someone the my mistake here?

  • 写回答

3条回答 默认 最新

  • drip5880 2018-05-28 02:01
    关注

    The mistake is not obvious, but quite a usual one: the "generic" greedy dot matching pattern followed with a series of optional subpatterns (patterns that can match an empty string).

    The \..*\/.*\/([^\/?]*)\/?$ pattern matches like this: \..* matches a . and then any 0+ chars as many as possible, then backtracking starts for \/ to match a / that is the rightmost / in the string (the last one), then .*\/ matches again any 0+ chars as many as possible and then makes the engine backtrack even further and forces it to discard the previously found / and re-match the / that is before to accommodate for another rightmost / in the string. Then, finally comes ([^\/?]*)\/?$, but the previous .*\/ already matched in the URL with / at the end, and the regex index is at the string end. So, since ([^\/?]*) can match 0+ chars other than ? and / and \/? can match 0 / chars, they both match empty strings at the end of the string, and $ calls it a day and the regex engine returns a valid match with an empty value in Group 1.

    Get rid of greedy dots, use a

    '~([^\/?]+)\/?$~'
    

    See the regex demo

    Details

    • ([^\/?]+) - Capturing group 1: one or more chars other than ? and /
    • \/? - 1 or 0 / chars
    • $ - at the end of the string.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)
编辑
预览

报告相同问题?

悬赏问题

  • ¥15 编写Linux测试服务启动失败
  • ¥20 matlab绘冲床平面连杆机构图和仿真,求帮助
  • ¥15 为什么树莓派5b显示禁止连接
  • ¥15 请专家处理报错!基于深度学习的车型分类问题:数据集为包含 10 种车型的图像数据集,分为训练集、验证集和测试集。
  • ¥20 流量太费!寻找便宜的app音视频SDK或平替方案。
  • ¥15 kubeasz部署遇到问题
  • ¥15 GUIDE to App Designer Migration Tool for MATLAB
  • ¥50 第三代非支配排序遗传算法(NSGA-Ⅲ)和多目标粒子群优化算法(MOPSO)的实现
  • ¥20 plant simulation与python com接口实时数据交互
  • ¥15 有关汽车的MC9S12XS128单片机实验
手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部