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:
Matching a few strings

 



yaronb
stranger

Aug 26, 2001, 4:51 AM

Post #1 of 3 (4440 views)
Matching a few strings Can't Post

How can I get a list of all matched strings ?

Say I have a string, $string1="a1 b2 c3"

If I set ($find_string)=$string1=~/\w\d/;
$find string will always equal "a1".

What is the way to get to the next matched string ?

Thanks,
Yaron.



mhx
Enthusiast

Aug 26, 2001, 7:47 AM

Post #2 of 3 (4439 views)
Re: Matching a few strings [In reply to] Can't Post

Hey, cool, it seems there's someone really interested in regular expressions. Wink

There are several ways to achieve what you want. But, first of all,

Code
$string1="a1 b2 c3"; 
($find_string)=$string1=~/\w\d/;

will always make $find_string equal 1, not 'a1'. So I'm sure you meant

Code
($find_string)=$string1=~/(\w\d)/;

If you supply a g modifier to the regex, it will return an array of all substrings matching the regex:

Code
@find_strings = $string1 =~ /(\w\d)/g;

Now @find_strings will contain all substrings, for the example this would be ('a1', 'b2', 'c3').
Another way would be to make a loop with the g-modifier:

Code
while( $string1 =~ /(\w\d)/g ) { 
print "Substring found: $1\n";
}

This will also find all matching substrings and is more useful if you want to catch several subexpressions, like

Code
while( $string1 =~ /(\w)(\d)/g ) { 
print "Character: $1, Digit: $2\n";
}

Hope this helps.

-- Marcus

P.S.: If you're interested in learning more about regexes, I recommend reading perldoc perlre. If you're still interested in learning more about regexes then, I recommend reading japhy's Regular Expressions in Perl and Jeffrey Friedl's Mastering Regular Expressions.
And, of course, keep on posting questions to this forum if you need help! Cool


Code
s$$ab21b8d15c3d97bd6317286d$;$"=547269736;split'i',join$,,map{chr(($*+= 
($">>=1)&1?-hex:hex)+0140)}/./g;$"=chr$";s;.;\u$&;for@_[0,2];print"@_,"



yaronb
stranger

Aug 27, 2001, 12:30 AM

Post #3 of 3 (4434 views)
Re: Matching a few strings [In reply to] Can't Post

Thanks for all your help !
Yaron.


 
 


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

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