Reputation: 1332
I don't know almost anything about regex, but I need to allow only one space between letters, this is what I have done with another questiona and answer, plus random tries with regex101:
/^(\d){1,}(\:[A-Za-z0-9-]+([ a-zA-Z0-9-]+)?)?\:(\d){1,}(?:\.(\d){1,2})?$/m
The fomat should be:
[integer]:[optional label :][integer/decimal]
Example:
12:aaa:12.31
56:a s f:15
34:45.8
I have done some random tries without any success,I'm only able to allow infinite space, could someone help me? I have also looked at others answers, but I couldn't implement in my regex.
Check if error:
preg_match_all('/^(\d+)(:[A-Z0-9-]+(?: [A-Z0-9-]+)*)?:(\d+(?:\.\d{1,2})?)$/mi', $_POST['ratetable'], $out);
if($out[0]!=explode("\n",$_POST['ratetable'])){
header('Content-Type: application/json; charset=utf-8');
echo json_encode(array(0=>'Invalid price table at line: '.implode(", ", array_diff_key(array_flip(explode("\n",$_POST['ratetable'])),array_flip($out[0])))));
exit();
}
Upvotes: 1
Views: 749
Reputation: 53831
I think
^\d+:([^:]+:)?\d+(\.\d+)?$
might do it...
It means: <int> + ":" + [label + ":"] + <float>
where label
can be anything but :
.
Upvotes: 2
Reputation: 5260
You can use preg_match
$str = 'Another Example String 1_2-3';
echo $str . "<br />\n";
if (preg_match('#^(?:[\w-]+ ?)+$#', $str)){
echo 'Legal format!';
} else {
echo 'Illegal format!';
}
Upvotes: 1
Reputation: 71548
You could make the regex a bit shorter and allow a single space in between each letter like this:
/^(\d+)(:[A-Z0-9-]+(?: [A-Z0-9-]+)*)?:(\d+(?:\.\d{1,2})?)$/gmi
If you want to capture only the label (and exclude the :
) in the capture, you can use this one.
Upvotes: 2
Reputation: 78463
You're nearly there:
(?: [a-zA-Z0-9-]+)*
the above would mean: space followed by at least one in the character group; the latter group any number of times, without capturing
Upvotes: 1