Search code examples
regexopencms

Regex conditional: give the user exactly two options


The user has to type in his/her customer number in a browser form. The backend is built with java-based OpenCMS.

The customer number consists of 8 alphanumerical, a slash then another 3 chars (i.e., 12 chars in total). However, sometimes users forget the slash. If the latter is the case, we just have 11 alphanumerical chars.

How to give the user the option to either write the customer number either with or without slash?

Valid inputs are:

a1234567/123
01234567/321

01234567890
a0123456789

Currently, I just managed to restrict regex to 12 alpha-numerical chars.

^[A-Za-z0-9]{12}$

We have to start with the ^-sign and end with the $-sign.


Solution

  • Matching regular expression:

    ^[a-zA-Z0-9]{8}\/?[a-zA-Z0-9]{3}$
    

    first exact 8 alphanumeric chars, then optional slash and exact 3 alphanumeric chars