سؤال

/([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?

هل كانت مفيدة؟

المحلول 2

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:

نصائح أخرى

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

/([a-zA-Z0-9\-])@(?1)/
                ^
              () not needed around the @ sign
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top