I am having trouble matching optional template groups in regex. The metacharacters * and + are greedy, so I thought about the metacharacter? will also be greedy, but it doesn't seem to work as I thought.
Theoretically, I suggested that if we decided to make the template group optional, if the group of templates was found in the string, it would be returned in the matching results, if it was not found, we would still get the general results of the match, but there is no match in the results.
What actually happens if my pattern matches in a string, it is not included in the matching results, the regular expression looks like it notices that a group of patterns is optional and just doesn't even try to match it.
If we set up a test and change this optional group of templates to non-optional, regex will include it in the results of the comparison, but this is only applicable for the test, because sometimes this template will not be available in a row.
The reason I need a match included in the results is because I need the matching results for analysis later.
Encase I did not describe this scenario very well; I have a very simple example that follows in PHP.
$string = 'This is a test, Stackoverflow. 2014 Cecili0n'; if(preg_match_all("~(This).*?(Stackoverflow)?~i",$string,$match)) print_r($match);
results
Array ( [0] => Array ( [0] => This ) [1] => Array ( [0] => This ) [2] => Array ( [0] => ) )
(Stackoverflow)? is an optional template, if we run the above code, although this template is available on line, it will not be returned in the matching results.
If we make this template group mandatory, it will be returned in the results, as in the following.
if(preg_match_all("~(This).*?(Stackoverflow)~i",$string,$match)) print_r($match);
results
Array ( [0] => Array ( [0] => This ) [1] => Array ( [0] => This ) [2] => Array ( [0] => Stackoverflow ) )
How can i achieve this? It’s important for me to get accurate data on how a match was found.
Thanks for any thoughts on this.