duanluangua8850 2017-10-23 17:12
浏览 26
已采纳

标签=值的正则表达式

I need to build a single regex to match this 2 kinds of line:

1)SBNID=304,MENAME=RV0714,MEID=122,CELLID=4,CELLNAME=LRV0714D

2)MBTS_ACN1_RJ/ETHPORT:Cabinet No.=0, Subrack No.=0, Slot No.=7, Port No.=0, Subboard Type=BASE_BOARD

The output must be: For the first (1):

SBNID , MENAME , MEID , CELLID , CELLNAME

For the second (2):

Cabinet No. , Subrack No , Slot No. , Port No , Subboard Type

PS: Since my code process each input by time, I need to process first the input one, then input 2, not both together

I already tried:

(?<![^:,])[^=]+

Works for the second case, but for the first case it not returns SBNID

I am using pcre(php) regex

  • 写回答

2条回答 默认 最新

  • dongzhan1570 2017-10-23 17:50
    关注

    If I understand your requirements correctly, you're looking for key/value pairs. This could be achieved via

    (?P<key>\b[A-Za-z\h.]+)=(?P<value>\w+)
    

    See a demo on regex101.com.


    Broken down this says:
    (?P<key>\b[A-Za-z\h.]+) # capture A-Z, a-z or horizontal whitespaces 
                            # into group "key"
    =                       # = literally
    (?P<value>\w+)          # capture A-Z, a-z, 0-9 and _ 
                            # into group "value"
    


    Glued together in PHP this would be:
    <?php
    
    $string = "SBNID=304,MENAME=RV0714,MEID=122,CELLID=4,CELLNAME=LRV0714D
    MBTS_ACN1_RJ/ETHPORT:Cabinet No.=0, Subrack No.=0, Slot No.=7, Port No.=0, Subboard Type=BASE_BOARD";
    
    $regex = '~(?P<key>\b[A-Za-z\h.]+)=(?P<value>\w+)~';
    
    preg_match_all($regex, $string, $matches, PREG_SET_ORDER);
    
    foreach ($matches as $match) {
        print_r($match);
    }
    
    ?>
    

    See a demo on ideone.com.

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

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作