douyou2732 2014-02-13 15:10
浏览 42
已采纳

正则表达式提取子串

really struggling with this...hopefully someone can put me on the right path to a solution.

My input string is structured like this:

66-2141-A-AC107-7

I'm interested in extracting the string 'AC107' using a single regular expression. I know how to do this with other PHP string functions, but I have to do this with a regular expression.

What I need is to extract all data between the third and fourth hyphens. The structure of each section is not fixed (i.e, 66 may be 8798709 and 2141 may be 38). The presence of the number of hyphens is guaranteed (i.e., there will always be a total of four (4) hyphens).

Any help/guidance is greatly appreciated!

  • 写回答

2条回答 默认 最新

  • duandange7480 2014-02-13 15:41
    关注

    This will do what you need:

    (?:[^-]*-){3}([^-]+)
    

    Regular expression visualization

    Debuggex Demo

    Explanation:

    • (?:[^-]*-) Look for zero or more non-hyphen characters followed by a hyphen
    • {3} Look for three of the blocks just described
    • ([^-]+) Capture all the consecutive non-hyphen characters from that point forward (will automatically cut off before the next hyphen)

    You can use it in PHP like this:

    $str = '66-2141-A-AC107-7';
    preg_match('/^(?:[^-]*-){3}([^-]+)/', $str, $matches);
    echo $matches[1];  // prints AC107
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)