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 pnpm 下载element-plus
  • ¥15 解决编写PyDracula时遇到的问题
  • ¥15 有没有人能解决下这个问题吗,本人不会编程
  • ¥15 plotBAPC画图出错
  • ¥30 关于#opencv#的问题:使用大疆无人机拍摄水稻田间图像,拼接成tif图片,用什么方法可以识别并框选出水稻作物行
  • ¥15 Python卡尔曼滤波融合
  • ¥20 iOS绕地区网络检测
  • ¥15 python验证码滑块图像识别
  • ¥15 根据背景及设计要求撰写设计报告
  • ¥20 能提供一下思路或者代码吗