RegExp (Options)

I have created a RegExp but need to add some other variables

Valid exp should allow an empty string - if not an empty string must be a number only or the following 000000-A-000000-000 as below.
I’m not sure how to add ‘conditionals’ in exp’s

/\d{6}-[A-Za-z]{1}-\d{6}-\d{3}/gm

Hi,

the | operator allows the regular expression to match if any one of a number of conditions is satisfied. E.g. /foo|bar/ will match “foo” or “bar”, but nothing else.

In your case you need to check for:

  • An empty string.
  • A string that is only numbers.
  • The specific format 000000-A-000000-000.

So you can do this:

/^$|^\d+$|^\d{6}-[A-Za-z]{1}-\d{6}-\d{3}$/gm

To test:

const regex = /^$|^\d+$|^\d{6}-[A-Za-z]{1}-\d{6}-\d{3}$/;

console.log(regex.test("")); // true
console.log(regex.test("1234567890")); // true
console.log(regex.test("123456-A-123456-789")); // true
console.log(regex.test("789-A-123456-123456")); // false
console.log(regex.test("JavaScript")); // false

Alternatively, test here:

1 Like

Throw your stones, but I would never use regex for such a scenario. If I have exact three states to check I would always use an if with three conditions.

Regex is great if you need to match patterns but not for fix values

How do you want to do either of those without a regex?

I understood the second requirement to be a string in this format:

six digits
minus
uppercase A-Z
six digits
minus
three digits

Not just the string “000000-A-000000-000”

Edit:

Or do you mean:

const val = ...

if (val === '') { 
  ...
} elseif (/^\d+$/.test(val)) {
  ...
} elseif (/^\d{6}-[A-Za-z]{1}-\d{6}-\d{3}$/.test(val)) {
  ...
}

Sorry you are right. I thought the value is a static one but his regex showed that it looks like a pattern

2 Likes