-2

I want to validate/write a regex of this form: uuid OR uuid-cust-uuid

It should ONLY return true when I test with a valid uuid OR a composed uuid like uuid-cust-uuid

Here is the regex I have written thus far:

  const uuid =
  /[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}(\-cust\-[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12})?/;

   

1 Answers1

-1

You can use the test method and it will do the job.

const regexUUID = /[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}(\-cust\-[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12})?/;

const uuid = 'ec3bf3c6-85be-4169-971c-0c49be945b51';

console.log(regexUUID.test(uuid));

Edited: As for your requirement, you can try something like this:

// Wrtie base uuid regex
const baseUUIDRegex = '[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}';

// Then use it inside another regex like this
const customRegex = `^${baseUUIDRegex}-cust-${baseUUIDRegex}$`;
console.log('ec3bf3c6-85be-4169-971c-0c49be945b51-cust-ec3bf3c6-85be-4169-971c-0c49be945b51'.match(customRegex));

Hope it will be helpful for you.

Ubaid
  • 737
  • 8
  • 18
  • I'm aware of the `test()` method for regex. My issue is writing a valid regex to suit those conditions originally raised @Ubaid Ullah – Olusegun Ekoh Oct 13 '22 at 13:43
  • Please see the edited version of the answer. You can write your regex like I demonstrated in the answer. const baseUUIDRegex = '[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}'; const UUIDRegex = `^${baseUUIDRegex}-cust-${baseUUIDRegex}$`; – Ubaid Oct 17 '22 at 11:07