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,813
  • 4
  • 25
  • 36
user3639768
  • 111
  • 1
  • 6

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
  • 8,340
  • 1
  • 31
  • 51
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
  • 13,530
  • 11
  • 51
  • 70