3

I am trying to create a regular expression to validate a code. The rules are as follows:

  • It starts with a B or J or 28
  • Total length of the string must be either 7 or 13 characters (including starting characters)
  • The characters following the starting characters must be all digits

Can anyone help me with this ? Thanks

I tried something like

$pattern = "/^((J|B|28)([0-9])({7}|{13})?/i";

But it doesn't seem to work :\

2 Answers 2

7
$pattern = "/^(?=(.{7}|.{13})$)(B|J|28)\d+$/";
Sign up to request clarification or add additional context in comments.

8 Comments

I always had problems with these regular expressions.. I don't know when I will start to learn using them :) good job Mike, I've also tested it and it works +1
Change it to /^(?=(.{7}|.{13})$)(B|J|28)\d+$/ and will work
Vote up for speed; but would rather see the edit explaining the subpatterns, delimiter use, back reference, etc... That's what contributes to getting DjMike (and everyone else) to the next level :) On a side note, his is case insensitive, yours isn't.
@Daniel true, my understanding of regular expressions is horrible :\
Have to admit clever use of the conditional check here, you can further simplify by changing ?=(.{7}|.{13} to ?=(.{7,13}
|
1

First use the following regular expression to match the pattern. It will capture the first identifier in the first group and the following digits in the second group.

<?php 
$pattern = "/^(B|J|28)([0-9]+)$/i"; 
?>

Then run strlen() to validate the length. Regular expressions are not a good tool to validate variable lengths across groups.

<?php 
$hasValidLength = strlen( $str ) === 7 || strlen( $str ) === 13; 
?>

6 Comments

He said total length must be between 7-13 including starting characters
i'll check. Thanks for the answers!
Wops. Then he should rather do a strlen() check after running the regular expression.
It doesn't match this for example: J100027872577
I think the idea (of the question) is to have a single regular expression to match against the code.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.