php - preg_match_all get the end of the expression
one text
Solution:
The match should end with a closing ]
but the Parameters
group can contain [
and ]
as well.
One option is to match as least as possible characters until you reach another part that starts with 3G or EL or the end of the string after the closing square bracket.
\[(?P<Manufacture>3G|EL)\*(?P<DeviceId>[0-9]{10})\*(?P<Length>[A-Z0-9]{4})\*(?P<Command>[^[,\r\n]*)(?:,(?P<Parameters>.*?(?=](?:\[(?:3G|EL)|$))))?]
Explanation
\[
Match[
(?P<Manufacture>3G|EL)\*
Named groupManufacture
match either3G
orEL
and*
(?P<DeviceId>[0-9]{10})\*
Named groupDeviceId
match 10 digits and*
(?P<Length>[A-Z0-9]{4})\*
Named groupLength
match 4 times one of A-Z or 0-9(?P<Command>[^[,\r\n]*)
Named groupCommand
match[
followed by any char except[
,
or a newline(?:
Non capture group,(?P<Parameters>.*?
Match a,
followed by any char as least as possible in groupParameters
(?=](?:\[(?:3G|EL)|$))
Positive lookahead to assert what is at the right is either[3G
or[EL
or the end of the string
)?
Close non capture group and make it optional]
Match closing]