doulu4534 2013-08-13 18:37
浏览 120
已采纳

写一个正则表达式来获取两个分隔符之间的数字

I need to parse a string and get the numbers between 2 delimiters. I need to be sure they're numbers. I tried something like this but doesn't work as expected.

if (preg_match_all("/[^0-9](?<=First)(.*?)(?=Second)/s", $haystack, $result))
for ($i = 1; count($result) > $i; $i++) {
    print_r($result[$i]);
}

What's wrong with the regex?

  • 写回答

2条回答 默认 最新

  • dongye6377 2013-08-13 18:40
    关注

    Huh, that's almost the one I supplied to your other question xD

    Change the (.*?) to ([0-9]+)

    if (preg_match_all("/(?<=First)([0-9]+)(?=Second)/s", $haystack, $result))
    for ($i = 1; count($result) > $i; $i++) {
        print_r($result[$i]);
    }
    

    .*? will match any character (except newlines) and to match only numbers in between your delimiters "First" and "Second", you will need to change it to [0-9]. Then, I assume that there can't be nothing in between them, so we use a + instead of a *.

    I'm not sure why you used [^0-9] in the beginning. Usually [^0-9] means one character which is not a number, and putting it there doesn't really do something useful, at least in my opinion.

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

报告相同问题?

悬赏问题

  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题