0

I want to name or reference a grouped pattern for reuse without enforcing a similar match across this pattern to shorten my regex.

I'm sure there are examples with more obvious benefit to doing something like this, but let's say I want to match something like a string composed of six 2-digit hex numbers separated by colons, such as 38:f8:b7:90:45:92.

The pattern I came up with for this is (?:[0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}

[0-9A-Fa-f]{2} is used to represent a 2-digit hex number, which I'll call the hex pattern. Instead of repeating this a second time after the colon, I'd like a way to name this or something so I can shorten my regex.

I've already tried (?:(?<x>[0-9A-Fa-f]{2}):){5}\k<x> but rather than being the original hex pattern I made, it seems to only match with the last match the hex pattern found. For example, running this regex on 38:f8:b7:90:45:92 will basically turn the pattern into ([0-9A-Fa-f]{2}):){5}45 since 45 is the last match the original hex pattern found.

Therefore only something like 00:18:12:c1:5a:5a, where the last two 2-digit numbers are the same, will match.

Is there a way to name a pattern for complete reuse?

Ethan B.
  • 105
  • 7
  • 1
    If it is pcre for example, you could recurse the first subpattern `(?:([0-9A-Fa-f]{2}):){5}(?1)` or by name `(?:(?[0-9A-Fa-f]{2}):){5}(?&x)` – The fourth bird Jun 16 '19 at 14:58
  • [Python](http://stackoverflow.com/questions/19794603/reuse-part-of-a-regex-pattern), [C#](http://stackoverflow.com/questions/8204214), [PHP](https://stackoverflow.com/questions/38992457), [Java](https://stackoverflow.com/questions/46466549). – Wiktor Stribiżew Jun 16 '19 at 17:11

1 Answers1

1

If supported, you could make use of repeating the subpattern

That might look like:

(?:([0-9A-Fa-f]{2}):){5}(?1)
   ^                    ^^^^

Regex demo

Or by name:

(?:(?<x>[0-9A-Fa-f]{2}):){5}(?&x)
   ^^^^^                    ^^^^^

Regex demo

The fourth bird
  • 154,723
  • 16
  • 55
  • 70