For once I’m under a deadline and need a little help. This should be trivial for those who know regex. I need a pattern for up to 4 alpha or number characters, dash, number.
These all would match
A-1
AAAA-12345
KY1-34343
These would not match
BBBBB-242 (too many letters at start)
fws242 ( no dash)
BB1-2B2C (no letters in second section)
^[A-Za-z0-9]{1,4}\-\d+$
Updated, as I just read up to (can it be zero?)
1 Like
Yes. Oh, one other thing - can’t start with a number.
^[^0-9]{0,1}[A-Za-z0-9]{0,3}\-\d+$
ummm, a lot of things could be “not a digit” no? I was thinking more like
/^[A-Z][A-Z0-9]{0,3}\-\d+$/i
We both still have bugs in it. As yours no longer permits starting with a dash.
^([A-Z][A-Za-z0-9]{0,3})?\-\d+$
Yeah, I just found it today. I usually use a different site, but couldn’t find it, so I searched for regex online tester and that one came up.
For those wondering what site it is: https://regex101.com/r/tX0kL1/1
See, this is what I hate about PHP regex. Your pattern works fine in Javascript, but server side validation with preg_match doesn’t work.
cpradio
December 9, 2014, 8:00pm
10
It should. Can you post the code you used?
Yes, the different flavors are just enough alike to make it easy and just enough different to make it difficult.
cpradio
December 9, 2014, 8:10pm
12
Here is what I have:
$input = array('A-1', 'AAAA-12345', 'KY1-34343', '-1234', '123-1234', 'BBBBB-242', 'fws242', 'BB1-2B2C', '1BBB-1234');
for ($i = 0; $i < sizeof($input); $i++) {
preg_match('/^([A-Z][A-Za-z0-9]{0,3})?\-\d+$/', $input[$i], $matches);
echo $input[$i] . ': ' . ((sizeof($matches) != 0) ? "Success\r\n" : "Failed\r\n");
}
Which produced:
A-1: Success
AAAA-12345: Success
KY1-34343: Success
-1234: Success
123-1234: Failed
BBBBB-242: Failed
fws242: Failed
BB1-2B2C: Failed
1BBB-1234: Failed
Nah, it was just simply a matter that when I’m unfamiliar with something and don’t have any confidence in it I focus on it. I was overlooking a misspelled variable. It works now. Thanks again.
1 Like
system
Closed
March 11, 2015, 8:00am
14
This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.