Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

reg exp

Status
Not open for further replies.

superstarjpmc

Programmer
Joined
Jan 22, 2004
Messages
38
Location
US
I have a string as below.

"o=this_is_p1,o=value"

I want to extract the value : 'this_is_p1' using a REG_EXP.

Can anyone help ?
regs
david j
 
Code:
print "$1\n" if /^([^,]+),/;
Or you could split on comma.




(very injured) Trojan.
 
Code:
$str = "o=this_is_p1,o=value";
$str =~ /=(.*),/;

print $1;

this will print: [blue]this_is_p1[/blue]


``The wise man doesn't give the right answers,
he poses the right questions.''
TIMTOWTDI
 
Hi David

Bit safer to go about this Trojan's way

i.e.

^ (caret) to force the regex to look from the start of the line
no use of .* - which could copy more than you require should you need to use this for longer strings with more commas in

Trojan's example is forcing the regex to start at the beginning of the line - which is what you require - then finding any non-comma characters. I guess this is exactly what you need


Kind Regards
Duncan
 
If you want it safe this is the way. Considering that the value you are searching for, might be somewhere in the middle.
Code:
$str = "a=this_is_p1,a=value1,b=this_is_p2,b=value2,o=this_is_p3,o=value3";
@str=split(/,/,$str);
foreach $i (@str){
  ($key, $value) = split(/=/, $i);
  if (exists $pairs{$key}){
    $key.="v";
  }
  $pairs{$key}=$value;
}
foreach $key(sort keys %pairs){
  print "$key:  $pairs{$key}\n";
}
This last print will give you this
Code:
a:  this_is_p1
av: value1
b:  this_is_p2
bv: value2
o:  this_is_p3
ov: value3
or if you want, lets say, the [blue]value2[/blue]
just
Code:
print $pairs{bv};
or if you want [blue]this_is_p3[/blue]
just
Code:
print $pairs{o};


``The wise man doesn't give the right answers,
he poses the right questions.''
TIMTOWTDI
 
Code:
"o=this_is_p1,o=value"
This looks like the query string part of a URL. If that is the case, use CGI.
 
Status
Not open for further replies.

Similar threads

Part and Inventory Search

Sponsor

Back
Top