Search code examples
regexpcre

How to match a line having 2 or more caracters, and that can have spaces, on a defined length?


I want to match a string beginning by an F or a C,

The length must be 13,

I can include spaces, numbers and capital letters, but I must have at least 2 non-space characters in the string.

I can't find how to fuse those conditions, could you please help me ?

I am using PCRE(PHP)

I tried a line looking like this:

^([C,F][0-9A-Z])(.*[0-9A-Z ]{1,12})$

But it seems it matches whenever I have 2 or more characters, even if the length is below 13


Solution

  • You may use

    ^(?=.{13}$)[CF] *(?:[0-9A-Z] *)+$
    

    Or

    ^(?=.{13}$)[CF]\s*(?:[0-9A-Z]\s*)+$
    

    See the regex demo

    Details

    • ^ - start of string
    • (?=.{13}$) - the string must be 13 chars long (add (?s) before ^ if the string may have line breaks)
    • [CF] - C or F
    • \s* - 0+ whitespaces
    • (?:[0-9A-Z]\s*)+ - 1 or more repetitions of
      • [0-9A-Z] - an uppercase ASCII letter or digit
      • \s* - 0+ whitespaces
    • $ - end of string.

    Note that since the [CF] already matches a non-space char, the (?:[0-9A-Z]\s*)+ already makes sure there is another non-space char later in the string.