dsp15140275697 2018-06-12 16:49
浏览 53
已采纳

与给定模式匹配的正则表达式,以可选数字结尾

I've been trying to use a regular expression to match and extract parts of a URL. The URL pattern looks like:

http://domain.abcdef/xyz/fe/fi/fo5/fu2m/123/

I intend to capture the following groups:

  1. match and capture xyz (optional, but specific value)
  2. match and capture fe/fi/fo5/fu2m (must exist, arbitrary value)
  3. match and capture 123 (optional numeric value, which must appear at the end)

Here are expressions I have tried and problem encountered:

string1: http://domain.abcdef/xyz/fe/fi/fo5/fu2m/123/

string2: http://domain.abcdef/xyz/fe/fi/fo5/fu2m/

^(?:https?:\/\/)?(?:[\da-z\.-]+)\.(?:[a-z\.]{2,6})(?:\/(xyz))?\/([\/\w]+)+(?:\/([\d]+))\/$
  • makes number at end mandatory

  • matches and captures all groups as required in string1 even when xyz is not included

  • no match in string2 because there's no number at the end

     ^(?:https?:\/\/)?(?:[\da-z\.-]+)\.(?:[a-z\.]{2,6})(?:\/(xyz))?\/([\/\w]+)+(?:\/([\d]+))?\/$
    
  • makes number at end optional

  • captures only groups 1 and 2 in string1 and string2 . Number is matched along with group 2 in string2 as fe/fi/fo5/fu2m/123

My problem is how to capture groups 1, 2 and 3 in all scenarios incl. string1 and string2 (note: I am using PHP's preg_match function)

  • 写回答

2条回答 默认 最新

  • dqask02082 2018-06-12 17:18
    关注

    I will use parse_url first to extract the path from the url. Then all you have to do is to use a non-greedy quantifier in the second group :

    $path = parse_url($url, PHP_URL_PATH);
    
    if ( preg_match('~^\A/([^/]+)/(.*?)/(?:(\d+)/)?\z~', $path, $m) )
        var_dump($m);
    

    This way, if the number at the end is missing, the non-greedy quantifier (from the second group) is forced to reach the end of the string.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分