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条)

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!