TheBlackCorsair
TheBlackCorsair

Reputation: 527

Match a sentence from a line in perl

I have the following question. How do you match a sentence, which is surrounded by commas(,), but the sentences can vary in size and number of words. For example:

Hi,How are you,bye

Thanks, I am very good,bye

So I want to match "How are you" and "I am very good" I have tried something like

 $_ =~ /,([\w\s\w\s\w,])/;

but that seems very wrong and will "possibly" match 3 words separated by space.

Upvotes: 1

Views: 2639

Answers (2)

Minko Gechev
Minko Gechev

Reputation: 25682

Here is an example:

if ($sentence =~ /,(.+?),/g) {
    print $1;
}

This will match the sentence and put the result into $1. If you have multiple sentences:

while (<>) {
    while (/,(.+?),/g) {
        print $1;
    }
}

This is an example with input from the standard input and getting only the values between commas.

(.+?) will match everything which length is more than 0 and is not a comma. Because of the () it will be saved into $1.

Upvotes: 2

Oleg V. Volkov
Oleg V. Volkov

Reputation: 22421

Wouldn't a simple /,(.+?),/ do? Or /,([\w\s]+?),/ if you want to be sure that you only have words and spaces?

my $str = "Hi,How are you,bye";

$str =~ /,([\w\s]+?),/;
print "$1\n";

$str = "Thanks, I am very good,bye";

$str =~ /,([\w\s]+?),/;
print "$1\n";

Upvotes: 5

Related Questions