Vasanth
Vasanth

Reputation: 201

Capturing Group with regex

I am using the code as follows,

Code:

 my $str = 123455;

if ($str =~ m/([a-z]+)|(\d+)/ {
   print "$1\n";
}

I know that it will not print the result because we should give $2. But I want to get the result as it is using the same code by changing the regular expression.

Is it possible to do it?

Note :

Please do not provide the result as below,

 my $str = 123455;

if ($str =~ m/(?:[a-z]+)|(\d+)/ {
   print "$1\n";
}

Upvotes: 1

Views: 77

Answers (4)

GWP
GWP

Reputation: 131

What do you mean you don't want to change your group structuring? You want your capture to go to group 1, but what you have won't ever put a number in group 1. You have to change your group structuring.
If you still want to be able to find a numeric in group 2, you can create subgroups -- groups number from the opening parenthesis. Try

([a-z]+|(\d+))

if that's what you want.

Upvotes: 0

You could use print "$&\n".

$& contains the entire matched string (in other words : either $1 or $2).

See http://perldoc.perl.org/perlre.html for more details ;-)

Upvotes: 0

mpapec
mpapec

Reputation: 50637

You can use (?| .. ) for alternative capture group numbering,

use 5.010; # regex feature available since perl 5.10

my $str = 123455;

if ($str =~ m/(?| ([a-z]+)|(\d+) )/x) {
   print "$1\n";
}

Upvotes: 3

vks
vks

Reputation: 67968

([a-z]+|\d+)

Try this.Replace by $1.See demo.

http://regex101.com/r/sZ2wJ5/1

Add anchors if you want to match only letters or numbers at a time.

^([a-z]+|\d+)$

or

((?:[a-z]+)|(?:\d+))

Upvotes: 1

Related Questions