dpj775835868 2019-07-07 16:27
浏览 91
已采纳

正则表达式与utf8中的逗号和相等字符匹配

How can I regex match with this format?

a1=q1,a2=q2,a3=q3,a4=q4 (this is correct sample and a characters will be utf-8)

a1=q1,a2=q2,a3=q3,a4=q4, (faulty sample)

If string have last comma character, how can I exclude last comma in regex?

My sample php code is:

$pattern="/^(\p{L}\=\p{L},?)*$/u";
$string1="a1=q1,a2=q2,a3=q3,a4=q4"; //correct
$string2="a1=q1,a2=q2,a3=q3,a4=q4,"; //incorrect
if (preg_match($pattern,$string1,$m)) { echo "correct"; } else { echo "incorrect"; }
if (preg_match($pattern,$string2,$m)) { echo "correct"; } else { echo "incorrect"; }
  • 写回答

2条回答 默认 最新

  • douzhang2092 2019-07-07 16:41
    关注

    My guess is that this expression,

    (?!.*,$)([\p{L}\p{N}]+=[\p{L}\p{N}]+),?
    

    might work, which here

    (?!.*,$)
    

    we would just add a not ending with comma statement.

    The expression is explained on the top right panel of this demo, if you wish to explore further or modify it, and in this link, you can watch how it would match against some sample inputs step by step, if you like.

    Test

    $re = '/(?!.*,$)([\p{L}\p{N}]+=[\p{L}\p{N}]+),?/m';
    $str = 'a1=q1,a2=q2,a3=q3,a4=q4
    a1=q1,a2=q2,a3=q3,a4=q4,';
    
    preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
    
    var_dump($matches);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 win11家庭中文版安装docker遇到Hyper-V启用失败解决办法整理
  • ¥15 gradio的web端页面格式不对的问题
  • ¥15 求大家看看Nonce如何配置
  • ¥15 Matlab怎么求解含参的二重积分?
  • ¥15 苹果手机突然连不上wifi了?
  • ¥15 cgictest.cgi文件无法访问
  • ¥20 删除和修改功能无法调用
  • ¥15 kafka topic 所有分副本数修改
  • ¥15 小程序中fit格式等运动数据文件怎样实现可视化?(包含心率信息))
  • ¥15 如何利用mmdetection3d中的get_flops.py文件计算fcos3d方法的flops?