I just cant get my head around regex, any help appreciated !
I have plenty of string data which may or may not contain the strings "1/10" or "2/10" or "2/18" etc. Basically, both the numerators and denominators could vary. And to make things more complex, some of the data entry operators may have put a space anywhere between the numerators and denominators !! So my inputs could be : "x/y" or "x / y" or "x/ y" or "x /y" or "x/y " .... and probably more combos :(
In any of these cases, I wish to identify if x and y are numbers, and if there is a "/" slash between them. Am hopeless at regex, please help
Am coding in php and I guess preg_match is what needs to be used. Thanks for reading.
$pattern = "%(\d+) */ *(\d+)%";
$test = array(
'half is 1/2',
'13/100 is your score',
'only 23 /90 passed',
'no idea here:7/ 123',
'24 / 25',
'1a/2b'
);
foreach($test as $t){
if(preg_match($pattern, $t, $matches))
echo "PASS: n:$matches[1], d:$matches[2]\n";
else
echo "FAIL: $t\n";
}
outputs:
PASS: n:1, d:2
PASS: n:13, d:100
PASS: n:23, d:90
PASS: n:7, d:123
PASS: n:24, d:25
FAIL: 1a/2b
if(preg_match('~^[0-9]+\s*/\s*[0-9]+$~',trim($subject))) {
// valid
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With