Skip to content

Instantly share code, notes, and snippets.

@Jeff-Russ
Last active February 21, 2017 17:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Jeff-Russ/0be8b0414b1ea5d45987ec732cc77afc to your computer and use it in GitHub Desktop.
Save Jeff-Russ/0be8b0414b1ea5d45987ec732cc77afc to your computer and use it in GitHub Desktop.
Regex Capture Checker (in PHP)
<?php
function regex_capture_checker($regex_pat, $strings) {
foreach ($strings as $k => $v) {
if (is_integer($k)) {
$string = $v;
$comp = false;
} else {
$string = $k;
$comp = $v;
}
$ret = preg_match($regex_pat, $string, $capts);
if ($comp!==false) echo $capts===$comp ? "PASS: ": "FAIL: ";
echo "preg_match returned '"; var_export($ret);
echo "' and captured: "; var_export($capts); echo"\n\n";
}
}
echo "===== simple test, with just PASS / FAIL ====== \n\n";
regex_capture_checker('/^([-+]?[\d]+\.?[\d]*)(\s*)(.*)$/', array(
'1.2.0',
'-1 tag',
'+2n',
'2.0',
));
echo "===== now try checking capture groups against expected output ====== \n\n";
regex_capture_checker('/^([-+]?[\d]+\.?[\d]*)(\s*)(.*)$/', array(
'1.2.0' => array ('1.2.0', '1.2', '', '.0'),
'-1 tag'=> array ('-1 tag','-1', ' ', 'tag'),
'+2n' => array ('+2n', '+2', '', 'n'),
'2.0' => array ('2.0', '2.0', '', '' ),
));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment