CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Regular Expressions:
How to return which part of the Regular Expression was triggered

 



Labrex
New User

Dec 1, 2008, 3:37 PM

Post #1 of 5 (2731 views)
How to return which part of the Regular Expression was triggered Can't Post

Hi, it's a little difficult for me to explain this, but is there any way to return the part of the regex that was used to match the pattern.

For example:

my $key = 'cd';

if ($key =~ /AB|CD|EF|GH/i)
{
# I want to print out the part of the regex that was used to
# to match the pattern. In this case it would be 'CD'.
}


Thank. I really appreciate your time.


KevinR
Veteran


Dec 1, 2008, 4:26 PM

Post #2 of 5 (2721 views)
Re: [Labrex] How to return which part of the Regular Expression was triggered [In reply to] Can't Post

There might be other ways, but you can use a capturing group () and display the match that way:


Code
my $key = 'cd';  

if ($key =~ /(AB|CD|EF|GH)/i) {
print "$1\n";
}

-------------------------------------------------


Labrex
New User

Dec 1, 2008, 4:34 PM

Post #3 of 5 (2718 views)
Re: [KevinR] How to return which part of the Regular Expression was triggered [In reply to] Can't Post

Thanks for your help Kevin, but when I tried that, it prints out 'cd' instead of 'CD'. But that may be okay since it's case insensitive. Thanks.


(This post was edited by Labrex on Dec 1, 2008, 4:35 PM)


KevinR
Veteran


Dec 1, 2008, 5:04 PM

Post #4 of 5 (2712 views)
Re: [Labrex] How to return which part of the Regular Expression was triggered [In reply to] Can't Post


Code
my $key = 'cd';   

if ($key =~ /(AB|CD|EF|GH)/i) {
print uc($1),"\n";
}

-------------------------------------------------


Labrex
New User

Dec 1, 2008, 5:21 PM

Post #5 of 5 (2711 views)
Re: [KevinR] How to return which part of the Regular Expression was triggered [In reply to] Can't Post

Thanks, you have been of great help. I really appreciate it.

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives