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 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示