3

I'd like to preface this with how little I know about RegEx.

I'm trying to get the following RegEx to work with Javascript/Typescript:

/^({)?(?(1)|(\()?)[0-9A-F]{8}(-)?([0-9A-F]{4}(?(3)-)){3}[0-9A-F]{12}(?(1)}|(?(2)\)))$/i

This is RegEx for determining if a string is a valid GUID (in any of the correct forms; as seen here: https://stackoverflow.com/a/136591). It works for Python and PHP, but not for Javascript since it doesn't support conditionals. How would you write this in such a way that Javascript can use it?

You can test it here: https://regex101.com/r/rosi2k/1/tests

Nxt3
  • 1,970
  • 4
  • 30
  • 52
  • 1
    That just looks scary, lol. – Ryan Wilson Feb 27 '18 at 20:00
  • @RyanWilson No kidding. – Nxt3 Feb 27 '18 at 20:04
  • @Jan Because it's an Angular application. I can't use what's in that question because it doesn't work if you remove `-` and put them in the incorrect spot. Use that RegEx in the tests I posted above and it doesn't work for all of them. – Nxt3 Feb 27 '18 at 20:11
  • Without braces/parenthesis: [`^[^\W_]{8}(-?)(?:[^\W_]{4}\1){3}[^\W_]{12}$`](https://regex101.com/r/rosi2k/5/tests) or without capturing: [`^[^\W_]{8}(?:-[^\W_]{4}|[^\W_]{4}){4}[^\W_]{8}$`](https://regex101.com/r/rosi2k/8/tests) – bobble bubble Feb 27 '18 at 21:53

1 Answers1

2

You can't use conditionals, so the only option is to expand what already exists. Starting with the innermost group (3), you can convert the following section to it's expanded counterpart:

(-)?([0-9A-F]{4}(?(3)-)){3}
(?:-([\dA-F]{4}-){3}|[\dA-F]{12})

Now the only thing left is to expand groups 1 and 2 that surround the rest of the regex as such:

^(?:{[\dA-F]{8}(?:-([\dA-F]{4}-){3}|[\dA-F]{12})[0-9A-F]{12}}|\([\dA-F]{8}(?:-([\dA-F]{4}-){3}|[\dA-F]{12})[0-9A-F]{12}\)|[\dA-F]{8}(?:-([\dA-F]{4}-){3}|[\dA-F]{12})[0-9A-F]{12})$

It's ugly, but it works with your tests as shown here

Jan
  • 42,290
  • 8
  • 54
  • 79
ctwheels
  • 21,901
  • 9
  • 42
  • 77
  • 1
    It's not ugly - [**it's ugly like hell**](https://giphy.com/gifs/quote-the-hunchback-of-notre-dame-charles-laughton-VBi0qdmGH0rO8) :-) – Jan Feb 27 '18 at 20:14