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 求帮我调试一下freefem代码
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图