0

I need to match a string inside brackets. It may consist of a) name, b) exactly 8 digits or c) a+b combined with ':' between. So, to sum up:

named
12345678
named:12345678

are valid options, but these are not:

named:
:12345678
named12345678

I tried to reuse 'name' and 'dd' named groups to avoid repeating subpatterns. However, it seems that group cannot be referenced if it wasn't used before. It also seems that the same situation is with \1-like capture accessor.

My current solution:

"^\\((?:(?'name'[^\\d]+)|((?'dd'\\d{2}){4})|\\k<name>:\\k<dd>)\\)$"

'dd' group is splitted into 2-digits chunks as I needed to parse it that way. C# flavour used.

Any ideas how to write it in an elegant, working way?

melpomene
  • 84,125
  • 8
  • 85
  • 148
myszor
  • 85
  • 9
  • Are you using the regex in .NET? It seems to me that `^\((?:\D+|\d{8}|\D+:\d{8})\)$` is short enough, why use named groups? – Wiktor Stribiżew Dec 29 '17 at 09:57
  • 2
    Just note that `\k` is still a backreference to Group "name", it does not recurse the group pattern, it only references the exact value that was captured before. – Wiktor Stribiżew Dec 29 '17 at 10:03
  • Yes, that's regex used in .NET. Named groups was used just for easy access to its values. Thanks for suggestion - it's kind of compromise between simplicity and functionality. Maybe it's a good option not to parse digits chunks via regex, but still could be inefficient in more complex cases (as subpatterns are just repeated). – myszor Dec 29 '17 at 10:45
  • 1
    Your "name" regex is wrong: it eats `:` (which it probably shouldn't if `:` is used as a separator). – melpomene Dec 29 '17 at 10:54
  • If I were to do this in Perl, I'd just use normal variables: `my $name = qr/[A-Za-z]+/; my $dd = qr/[0-9]{8}/; my $regex = qr/\A(?:$name:$dd|$name|$dd)\z/;` – melpomene Dec 29 '17 at 11:00
  • Thanks. Of course subpatterns can be used also here, but I was curious how to do it in pure, single regex pattern (if it's possible at all). – myszor Dec 29 '17 at 11:19
  • 1
    See https://stackoverflow.com/a/44994445/3832970 – Wiktor Stribiżew Dec 29 '17 at 11:20

0 Answers0