user1783150
user1783150

Reputation: 281

Perl Regex - print all matches found in a string

Hopefully there isn't a major issue with this repost, I just needed some extra info that somehow slipped my mine the first time.

In the program I'm working on, I'm attempting to take in a txt file, then print the bits of txt contained in a pair of quotation marks.

Below is what I had. (Assume I've taken in the txt file and put it into an array with each line as an array element.) It works, but if a line has 2+ strings obviously it only prints the first.

What would be a clean way of printing all matches?

I tried iterating through $1, $2, $3, etc, and print them if ne "";. But this didn't seem to work.

txt file contents:


Lorem ipsum dolor sit amet
consectetur "adipisicing elit"
sed "do" eiusmod tempor "incididunt"
ut "labore et dolore" magna aliqua


CODE:
foreach(@arr)
{
    print "$1\n" if /(".*?")/g;
}

Upvotes: 1

Views: 1863

Answers (2)

Miller
Miller

Reputation: 35198

Use a while loop

foreach (@arr) {
    while (/(".*?")/g) {
        print "$1";
    }
}

Upvotes: 0

Pedro Lobito
Pedro Lobito

Reputation: 98921

Try this:

while ($subject =~ m/"(.*?)"/sig) {
    # matched text = $&
}

Upvotes: 2

Related Questions