dps123456789 2018-05-28 09: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 10: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条)

报告相同问题?

悬赏问题

  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元