1

I am trying to build a regular expression with the rule:

2 letters, or no letter followed by up to 6 numbers followed by up to three letters but the letters do not have to be included

(Suffix could be F, L, SD or SDL)

e.g. CA123456SDL OR CA123456 OR 123456

This must accept both upper and lower case.

so far I have came with below:

^([aA-zZ]{2}[0-9]{6,6}[F|L|SDL|SD]{0,1}$)

But its not applying the [F|L|SDL|SD]{0,1} rule and now sure how to add same for lower case , any idea how to achieve this?

bitsapien
  • 1,753
  • 12
  • 24
User
  • 79
  • 1
  • 11

3 Answers3

1

Note that [aA-zZ] is equal to a [A-z] pattern and it does not only match letters. [F|L|SDL] matches a single char from the set: F, |, L, S or D as it is a character class and not a grouping construct. Note that {6,6} is equal to {6}. I would stick to [0-9] like in your pattern as, in .NET, \d matches more than just ASCII [0-9].

You may use

(?i)^(?:[A-Z]{2})?[0-9]{6}(?:F|L|SDL?)?$

See the .NET regex demo

Details

  • (?i) - case insensitive modifier option
  • ^ - a start of a string anchor
  • (?:[A-Z]{2})? - an optional sequence of any two ASCII letters (use \p{L} instead of [A-Z] to match any Unicode letter)
  • [0-9]{6} - six ASCII digits
  • (?:F|L|SDL?)? - an optional occurrence (1 or 0 times) of F, L, SD or SDL
  • $ - end of string.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
0

the regex itself will be: [a-z]{0,2}[0-9]{6}[SDL]* with case insensitive modifier

$re = '/[a-z]{0,2}[0-9]{6}[SDL]*/mi';
$str = 'CA123456SDL OR CA123456 OR 123456';

preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);

// Print the entire match result
var_dump($matches);

Working example: https://regex101.com/r/6WOyrH/1

Unamata Sanatarai
  • 6,475
  • 3
  • 29
  • 51
0

You have couple of problems in your regex,

^([aA-zZ]{2}[0-9]{6,6}[F|L|SDL|SD]{0,1}$)

[aA-zZ] needs to be corrected to [a-zA-Z] [0-9]{6,6} is fine but can be compactly written as \d{6} I guess you intended to write [F|L|SDL|SD] as (F|L|SDL|SD)

If you want first two characters be there or completely missing, you need to write it like this,

([a-zA-Z]{2})?

Hence your updated regex should be this,

^([a-zA-Z]{2})?\d{6}(F|L|SDL?)?$

Here is a demo

Let me know if this works fine for you.

Pushpesh Kumar Rajwanshi
  • 18,127
  • 2
  • 19
  • 36