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"; }
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.
$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);
You're almost there, all you need to match last group without any ,
,
You can use this
^(\p{L}+\d+\=\p{L}+\d+,)*(\p{L}+\d+\=\p{L}+\d+)$