Reputation: 33
I have a string being received from a monitoring system, the string contains 3 variables that I am interested in the variables are pre/post fixed with c=VAR1; e=VAR2; s=VAR3;
so I want to grab the text in between for example c= ; but am having limited success, these are a few of the REGEXs I have tested with:
c=([^;]+);
.+c=(.+);.+
(?<=c=\()(.*?)(?=\;*\))
c=(.*);
A full alert string would look similar to:
alert c=Vari Able1; e=Vari Able2; s=Vari Able3;
But none seem to return in the way I would expect.
Any help is much appreciated.
Thanks!
Upvotes: 3
Views: 2871
Reputation: 33
So the ultimate solution to this question was I need to find out a little more about the tool I was using, specifically the REGEX engine... as it turns out it uses PCRE so the final REGEX was:
'(?<=c=)[^;]*'
'(?<=e=)[^;]*'
'(?<=s=)[^;]*'
In the tool that exists within the software I was reconfiguring this gave me the three variables I needed to correctly interpret my monitor system alerts.
Thanks all!
Upvotes: 0
Reputation: 50573
Your first regex is good, but only working for c
variable, this is a variation working for all three variables:
[ces]=([^;]+);
that will look for your c , e and s variables.
In PHP you could execute it like this:
$string = 'c=VAR1; e=VAR2; s=VAR3;';
preg_match_all("/([ces])=([^;]+);/", $string, $out, PREG_PATTERN_ORDER);
$tot = count($out[1]);
for ($i=0;$i<$tot;$i++) {
echo $out[1][$i]; //will echo 'c' , 'e' , 's' respectively
echo $out[2][$i]; //will echo 'VAR1' , 'VAR2' , 'VAR3' respectively
}
Update: Answer to a OP's question in comments
The above loop is for dinamically assign the values found, so if the regex found 4 , 5 or 10 vars the for will loop all of them. But if you are sure your string has only 3 vars in it, you could assign them directly in one go, like this:
$string = 'c=VAR1; e=VAR2; s=VAR3;';
preg_match_all("/([ces])=([^;]+);/", $string, $out, PREG_PATTERN_ORDER);
$$out[1][0] = $out[2][0]; // var $c is created with VAR1 value
$$out[1][1] = $out[2][1]; // var $e is created with VAR1 value
$$out[1][2] = $out[2][2]; // var $s is created with VAR1 value
echo $c; //will output VAR1
echo $e; //will output VAR2
echo $s; //will output VAR3
I'm using PHP variable variables in above code.
Upvotes: 0
Reputation: 263733
Try something like this,
(?<=((alert)?.*=)).*?(?=;)
See Lookahead and Lookbehind Zero-Width Assertions.
RegexBuddy ScreenShot
Upvotes: 0
Reputation: 101614
You can use something like:
(\w+)=([^;]+)
Which would grab all values (key and value), but if you're after only the c value:
c=([^;]+)
Should capture everything between the =
and ;
(([^;]+)
captures every character that's not a semi-colon, repeated 1 or more times.).
Upvotes: 1