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 Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

replace last REGEX match

Status
Not open for further replies.

RottPaws

Programmer
Mar 1, 2002
478
US
I have a string of comma delimited numbers and I want to replace the last comma with ' and '.

I can write a regexp to find the last instance of ', ', but I haven't been able to figure out how to replace just that. It drops the last order number from the string
Code:
$ord_list = '12345678, 23456789, 34567890, 98745632';
$ord_list =~ s/(, )\d+$/ and /;

result: $ord_list = '12345678, 23456789, 34567890 and '

_________
Rott Paws

...It's not a bug. It's an undocumented feature!!!
 
I figured it out using the lookahead assertion.

Code:
$order_list =~ s/(, )(?=\d+$)/, and /;

_________
Rott Paws

...It's not a bug. It's an undocumented feature!!!
 
Here's another way, with a less complicated substitution.
Code:
$_ = '12345678, 23456789, 34567890, 98745632';
s/(.+),/$1 and/ && print;
Which prints
Code:
12345678, 23456789, 34567890 and 98745632
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top