Reusing a character class in a regular expression

To keep the regex more concise, is there a shorthand way to refer to a character class that occurs earlier in the same regex?

Example

Is there a way to shorten the following:

[acegikmoqstz@#&].*[acegikmoqstz@#&].*[acegikmoqstz@#&]

+2


source to share


1 answer


Be aware that regular expression functions are language dependent.

With Java, you can do this:

[acegikmoqstz@#&](?:.*[acegikmoqstz@#&]){2}

      



But that's all, with java, you cannot reference a named subpattern.

With PHP, you can do this:

(?(DEFINE)(?<a>[acegikmoqstz@#&]))\g<a>(?:.*\g<a>){2}

      

+1


source







All Articles