doupai6875 2017-05-29 18:36
浏览 48
已采纳

正则表达式匹配终止符加上可变字符序列

Sorry to bother, I feel permanently lost when it comes to regex...

I have to match a string which occurs in a longer sequence of hex-values. My test-string is this:

BF1301020302000017BF1301030101010300FF6ABF130201010300FFC0BF1303010303030100FF98

Pattern is this:

  • starts with BF13
  • followed by an unknown amount of "01", "02" or "03" repetitions (\w\w)
  • 00 marks the termination of the sequence between BF13 and 00
  • after the 00-terminator, there are always 4 additional chars

I tried BF13(\w\w)+?00(\w\w){1} but it's obviously wrong.

The test-string is supposed to match and output these values:

  • BF1301020302000017
  • BF1301030101010300FF6A
  • BF130201010300FFC0
  • BF1303010303030100FF98

Thanks, guys!

  • 写回答

2条回答 默认 最新

  • dsc71976 2017-05-29 19:23
    关注

    This one will do the job :

    BF13(?:0[123])+00[A-Z0-9]{4}

    Explanation

    BF13 BF13 literally

    (?:...)+ Followed by something (non capturing group) at least one time (+)

    0[123] a zero followed by 1, 2 or 3

    00 Followed by 00

    [A-Z0-9]{4} Followed by uppercase char or a digit 4 times

    RegExp Demo

    Sample PHP code Test online

    $re = '/BF13(?:0[123])+00[A-Z0-9]{4}/';
    $str = 'BF1301020302000017BF1301030101010300FF6ABF130201010300FFC0BF1303010303030100FF98';
    
    preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
    
    foreach ($matches as $val) {
        echo "matched: " . $val[0] . "
    ";
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路