I have some lines:
[3G*2110620000*000A*UD]
[3G*2110620000*000A*LK][3G*2110620000*000A*LK,0,0,100]
[3G*2110620000*000A*LK,100]
[EL*2110620006*000A*LK,0,0],100]]]
I need to get an array as a result:
Array(
[0] => Array
(
[Manufacture] => 3G
[DeviceId] => 2110620000
[Length] => 000A
[Command] => UD
),
[1] => Array
(
[Manufacture] => 3G
[DeviceId] => 2110620000
[Length] => 000A
[Command] => LK
),
[2] => Array
(
[Manufacture] => 3G
[DeviceId] => 2110620000
[Length] => 000A
[Command] => LK
[Parameters] => 0,0,100
),
[3] => Array
(
[Manufacture] => 3G
[DeviceId] => 2110620000
[Length] => 000A
[Command] => LK
[Parameters] => 100
),
[4] => Array
(
[Manufacture] => 3G
[DeviceId] => 2110620000
[Length] => 000A
[Command] => LK
[Parameters] => 0,0],100]]
),
)
Each line can contain one or more commands.
- The command starts with "[" and ends with "]".
- The command must contain the manufacturer's name "3G" or "EL" after "[".
- Next comes the "*" separator.
- Next comes a 10-digit number is the device identifier.
- Next comes is a 4-byte packet length.
- Next comes a name of command (can be of arbitrary length).
- Next comes the "," separator.
- Next comes the command parameters (they may not be there, they can contain any characters, including "]" and "[").
I am trying to write a regex for these cases, but I am unable to highlight the parameters.
I tried
\[(?P<Manufacture>3G|EL)\*(?P<DeviceId>[0-9]{10})\*(?P<Length>[A-Z0-9]{4})\*(?P<Command>.+)[\]|,]{1}(?P<Parameters>.*)\]?
Demo: https://regex101.com/r/Iq2Xf4/2
My Answer:
To capture the parameters in your regex, you can modify the regex pattern as follows:
php
$pattern = '/\[(?P3G|EL)\*(?P[0-9]{10})\*(?P[A-Z0-9]{4})\*(?P[^\[\]]+)(?:,(?P[^\[\]]+))?\]/';
In this pattern, I have changed the `.+` in the `Command` group to `[^\[\]]+` to match any character except `[` and `]`. Additionally, I have added `(?:,(?P
This pattern will now correctly capture the parameters in your input lines.
Rate this post
4 of 5 based on 9808 votesComments