ash
ash

Reputation: 1200

perl regex to match all words following a character

I am no expert with Perl and regex. So here is my question.

How would I write a regex for matching all words in a string to the right of a specified character and retrieve each word separately in Perl?

I don't understand how I could match unspecified number of words and then most importantly retrieve it one at a time? If that is not possible what is my best bet in Perl to get this done?

E.G.: I have a C assignment like b=var1+var2. I want to be able to extract var1 and var2 if it exists. The important thing is I do not want to match a specific var1 and var2, but any variable after the assignment operator.

Thanks for the help!

Upvotes: 1

Views: 2938

Answers (3)

ephemient
ephemient

Reputation: 204678

\G/pos may be useful.

$_ = 'b=var1+var2';
# force further /g matches to start after the first '='
/=/g;

while (/(\w+)/g) {
    print "$1\n";
}

# prints
# var1
# var2

Upvotes: 3

Kenosis
Kenosis

Reputation: 6204

Perhaps the following will work for you:

use Modern::Perl;

my $string = 'b=var1+var2';
my $after  = '=';

say for ( $string =~ /$after(.*)/ )[0] =~ /(\w+)/g;

Output:

var1
var2

Hope this helps!

Upvotes: 1

Tyson
Tyson

Reputation: 1715

You can use nested groups in a regex. So for example the following regex should match all of the words (defined as \w, but you could tweak that) in your equation after the equals character (delimited by not \w, but you could tweak that as well):

=((?<Word>\w*)[^\w]*)*

Upvotes: 0

Related Questions