1
/([a-zA-Z0-9\-])(@)([a-zA-Z0-9\-])/

In the regex above group 1 and group 3 contain same expression. Is there another way to use the same expression in another group beside typing it all over again?

Delimitry
  • 2,987
  • 4
  • 30
  • 39
user3639768
  • 121
  • 1
  • 7

2 Answers2

2

If you are using PCRE, then you can do this:

/([a-zA-Z0-9\-])@(?1)/
                ^
              () not needed around the @ sign
Vasili Syrakis
  • 9,321
  • 1
  • 39
  • 56
1

If you want to re-use a group, you could use recursion:

/([a-zA-Z0-9\-])(@)(?1)/

(?1) will use the pattern from group 1. Let's now polish your regex:

  1. Remove unnecessary group: /([a-zA-Z0-9\-])@(?1)/
  2. We don't need to escape a hyphen at the end of a character class: /([a-zA-Z0-9-])@(?1)/
  3. Let's use the i modifier: /([a-z0-9-])@(?1)/i

Online demo

Further reading:

Community
  • 1
  • 1
HamZa
  • 14,671
  • 11
  • 54
  • 75