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 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动