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!

How to Remove a pattern (from the right)

Status
Not open for further replies.

cptk

Technical User
Mar 18, 2003
305
US
In ksh,
${var%%pattern}
%% will remove the longest matching pattern from the right.
% will remove the shortest matching pattern from the right.

so if ...
var="abc7xyz"
echo ${var%7*} ## would display "abc"

How would I do something like this in perl?
 
Try these...

For "%%":
Code:
$var = "abc7xyz7xyz";
($pvar = $var) =~ s/(.*?)7.*$/$1/;
print "$pvar\n"; # will print "abc"
For "%":
Code:
$var = "abc7xyz7xyz";
($pvar = $var) =~ s/(.*)7.*$/$1/;
print "$pvar\n"; # will print "abc7xyz"
 
perl has no equivalent syntax to what you posted. You can try the suggestions posted by CJason or describe better what you need to do. Your example is also confusing because it seems that the shortest match is 7x not 7xyz so I would think the example code would display abcyz instead of abc.

------------------------------------------
- Kevin, perl coder unexceptional! [wiggle]
 
You should take a look at non-greedy matching. It will slow down the match, but you should be able to do what I think you're looking for.
 
Thanks everyone - the purpose of my orig. post was to see how to handle trimming a string. What CJason suggestions works very nicely ...

For removing the longest matching pattern (%%), I went with:
$var = "abc7xyz7xyz";
($pvar = $var) =~ s/7.*$//;
print "$pvar\n"; # prints "abc"

but ... to to remove the shortest you do have to do something like CJason used (Bracket delimited sub-patterns).

 
How about:
Code:
$var = "abc7xyz7xyz";
($pvar = $var) =~ s/7[^7]*$//;
print "$pvar\n"; # prints "abc7xyz"
 
ishnid - thanks!!!

That's even better for matching the shortest pattern - using a negated character class
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top