in reply to Getting Data from Between Two Commas

split is likely the most appropriate solution here, as bart mentioned. However, in the spirit of TIMTOWTDI, here is a regex solution:

use strict; use warnings; my @text = ( "So, I went to the store and I wanted to buy a book, but it was to +o expensive, so\nI went home", "So, I went to the store and I wanted to buy a book, but it was\nt +oo expensive, so I went home", "So, I went to the store and I wanted to\nbuy a book, but it was t +oo expensive, soI went home", ); my $query = 'store'; foreach my $teststr ( @text ) { $teststr =~ m/ $query # query string [^,]* # zero or more chars that are not a co +mma , # followed by one comma ( # begin capture [^,]* # zero or more chars that are not a co +mma ) # end capture , # followed by one comma /x; print "found: [$1]\n" if $1; }
Output:
found: [ but it was too expensive] found: [ but it was too expensive] found: [ but it was too expensive]

I added a few comments to help you understand what was going on, but please take some time to read perlre. It will serve you well in the future. Extending this example to trim extra white space and to find multiple matches in the source text is left as an exercise to the reader.

Update: Also, think about how else a comma might be used and how that will affect how you find and process matches in the text. For example, could commas be used as separators in numbers? What if the text read "...buy a book that cost $1,234.00, but..."?

If, as bart suspects, this is homework (and I hope it is not), please please please make sure you fully understand how whatever code you use actually works, and the reasons for choosing that method over another. It will come back to bite you if you don't.