Link to home
Start Free TrialLog in
Avatar of Purdue_Pete
Purdue_Pete

asked on

Perl Parse String Question

Hi,
I have a question on string regex in Perl. I have strings like

user/112312312789071820883/label/qwe
user/112312312789071820883/state/asdas/cvbv
user/-/state/asdas/cvbv

I would like to get third substrin, i.e. label or state in the above case. Hoe can I get that in Perl?

Thanks.
ASKER CERTIFIED SOLUTION
Avatar of marchent
marchent
Flag of Bangladesh image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Purdue_Pete
Purdue_Pete

ASKER

marchent,
Since it is a single string for each "user/....", I guess i will just replace m by s, right?

Can you explain what this line does in your code in detail?
print $string =~ m|^[^/]*/[^/]*/([^/]*)|;

K

while(<DATA>) {
	my $third1 = (split/\//)[2];
	my ($third2) = m|.*?/.*?/(.*?)/|;
	
	print "third=$third1, $third2\n";
}
 
__DATA__
user/112312312789071820883/label/qwe
user/112312312789071820883/state/asdas/cvbv
user/-/state/asdas/cvbv

Open in new window

Avatar of ozo
(split'/')[2]
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
neither /m nor /s is necessary
m just allows ^ and $ to match at the beginning and end of lines in addition to the beginning and end of the string,
s just allows . to match "\n"

my ($third2) = m|/.*?/(.*?)/|;
marchent / ozo,
From this line,
print $string =~ m|^[^/]*/[^/]*/([^/]*)|;

I do get 'state' or 'label'. How can I store that in a variable?

K

my $third = $string =~ m|^[^/]*/[^/]*/([^/]*)|;

Open in new window

my ($third) = $string =~ m|/[^/]*/([^/]*)|;