Training, Open Source computer languages
PerlPHPPythonMySQLApache / TomcatTclRubyJavaC and C++LinuxCSS 
Search for:
Home Accessibility Courses Diary The Mouth Forum Resources Site Map About Us Contact
return part of a string that matches a pattern?

Posted by khuennekens (khuennekens), 13 January 2003
I am reading in a file as a long string.  There are certain key words in this file that separate different pieces of information.  As an example, let's say you have a string like this: "one here is some information two here's some other info three even more info four it's all different five", and you want to know what is the information between the words "two" and "three".  I can easily ask for a match m/two.*three/ but how can i find out what the actual pattern that matched is?  how do i find out what's between two and three?  This really has me stumped.  Thanks!  

Posted by admin (Graham Ellis), 13 January 2003
If you put round brackets round the "interesting bits" that you want to extract, they'll be saved into the special variable $1.

Example:

Code:
[localhost:~/jan03] graham% cat mat
$text = "One two and three then four and finally five";
$text =~ /two(.*)three/;
print "We got $1 out of that!\n";
[localhost:~/jan03] graham% perl mat
We got  and  out of that!
[localhost:~/jan03] graham%


If you use more than one set of brackets, you'll also get $2, $3, etc ... and if you save the result of the match into a list, you can get the results into a named variable as well.

Add a "g" modifier after the final /, and you get a global match - in a scalar context it will give you the next match each time (use that in a loop), and in a list context it gives you  a list of all matches.

Perl is a very exciting language - lots of ways to do anything  



This page is a thread posted to the opentalk forum at www.opentalk.org.uk and archived here for reference. To jump to the archive index please follow this link.

You can Add a comment or ranking to this page

© WELL HOUSE CONSULTANTS LTD., 2014: Well House Manor • 48 Spa Road • Melksham, Wiltshire • United Kingdom • SN12 7NY
PH: 01144 1225 708225 • FAX: 01144 1225 899360 • EMAIL: info@wellho.net • WEB: http://www.wellho.net • SKYPE: wellho