in reply to Regexp dashes at boundaries

You don't always need alternation, especially if most of the stuff on either side is the same. You can use the ? quantifier to denote some parts as optional.

This example works for the input you showed, but other forms you might find might require it to change a bit.

#!/usr/bin/perl $text = <<"HERE"; U.S. Army the Army has been berry-berry good to me US-Army US Army HERE $text =~ s/(?:U.?S.?[\s-])*Army/US-Army/g; print $text;
--
brian d foy <bdfoy@cpan.org>

Replies are listed 'Best First'.
Re^2: Regexp dashes at boundaries
by cormanaz (Deacon) on Mar 21, 2005 at 22:29 UTC
    Yes that does it. Now can I ask why you use the (?:...) extension? I tried it without and it works. I assume you have a good reason for putting it in there, but I looked up that regexp extension in the Camel book and the explanation is...um...sort of cryptic: "This is for clustering, not capturing; it groups subexpressions like ``()'', but doesn't make backreferences as ``()'' does." Thanks for the help... Steve

      I used the non-capturing parentheses to create a group so I could apply a quantifier to it. I want the "U.S. " to be optional, so I want to apply a * to that whole group. I should probably have used a ? (zero or one) though.

      --
      brian d foy <bdfoy@cpan.org>