John Davidson

php - preg_match_all get the end of the expression

0 comments
Message:


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.



  1. The command starts with "[" and ends with "]".

  2. The command must contain the manufacturer's name "3G" or "EL" after "[".

  3. Next comes the "*" separator.

  4. Next comes a 10-digit number is the device identifier.

  5. Next comes is a 4-byte packet length.

  6. Next comes a name of command (can be of arbitrary length).

  7. Next comes the "," separator.

  8. 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[^\[\]]+))?` to capture the parameters if they exist after the command.

This pattern will now correctly capture the parameters in your input lines.

Rate this post

4 of 5 based on 9808 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us