Am getting a response that looks like this:
{Delta=[r3, r4], X=alarmOff, Y=heatOn}
and using the preg_match I want filter out all the other a left on matches with r3r4
preg_match('/^{Delta=(\[.*\, .*\])}$/', $response[0], $matches)
am thinking something like this but am facing problems.
CodePudding user response:
use regex101 to test the regex.
in your code, if you drop off the closing brace and $ the match works and returns the text enclosed in square brackets.
$matchText = '' ;
$isMatch = preg_match('/^{Delta=(\[.*\])/', $response[0], $matches)
if ( $isMatch )
{
$matchText = $matches[1] ;
echo "got match: $matchText \n";
}
CodePudding user response:
Please try:
$pattern = "/^{Delta=\[(.*)\](.*)$/";
$response[0] = "/^{Delta=\[(.*)\](.*)$/";
preg_match($pattern, $response[0], $matches);
print_r($matches[1]);
CodePudding user response:
You can use a negated character class [^ to rule out the characters that are not allowed to match:
{Delta=(\[[^][,]*,[^][]*])[^{}]*}
{Delta=Match literally(Capture group 1\[Match[[^][,]*,Match 0 times any char other than[],and then match the,[^][]*Optionally match any char except[and]]Match]
)Close group 1[^{}]*Match 0 times any char other than{and}}Match}
Example printing the group 1 value:
$re = '/{Delta=(\[[^][,]*,[^][]*])[^{}]*}/';
$str = '{Delta=[r3, r4], X=alarmOff, Y=heatOn}';
preg_match($re, $str, $matches);
print_r($matches[1]);
Output
[r3, r4]
To get the separate matches for r3 and r4 you can use 2 capture groups:
{Delta=\[([^][,]*),\h*([^][]*)][^{}]*}
