in reply to regex needed: Capture a single entity from two discontiguous parts.

The best solution is probably to do a match followed by a substitution, as suggested by jettero, BrowserUk and explorer but it can be done with a regular expression, or two in fact. The first uses regular expression recursion to successively match groups of digits followed by a comma or closing parenthesis, appending the captured digits to a variable using a code block. The second initialises the variable then incorporates the first.

use strict; use warnings; use re q{eval}; my @numbers = ( q{Number... ()}, q{Number... (1)}, q{Number... (12)}, q{Number... (123)}, q{Number... (1,234)}, q{Number... (12,345)}, q{Number... (123,456)}, q{Number... (1,234,567)}, q{Number... (12,345,678)}, q{Number... (123,456,789)}, q{Number... (1,234,567,890)}, q{Number... (1,234a)},); my $deCommafied; my $rxNumberGrps; $rxNumberGrps = qr {(?x) \D* (\d+) (?=,|\)) (?{$deCommafied .= $^N}) (?: (??{$rxNumberGrps}) | \)\z ) }; my $rxDeComma = qr {(?x) (?{$deCommafied = q{}}) $rxNumberGrps }; foreach my $number (@numbers) { print qq{$number - }, $number =~ m{$rxDeComma} ? qq{$deCommafied\n} : qq{no match\n}; }

Here's the output.

Number... () - no match Number... (1) - 1 Number... (12) - 12 Number... (123) - 123 Number... (1,234) - 1234 Number... (12,345) - 12345 Number... (123,456) - 123456 Number... (1,234,567) - 1234567 Number... (12,345,678) - 12345678 Number... (123,456,789) - 123456789 Number... (1,234,567,890) - 1234567890 Number... (1,234a) - no match

As I said, the match and substitute approach is much simpler and easier to understand. This solution is far too complicated to maintain and was done more for the challenge as I'm not very good at recursion.

Cheers,

JohnGG