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