Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Help monks! I am writing a CGI script that takes user input and spits out silly things. One thing I can't seem to do correctly is substitute for any 'word' in my string that has a suffix, like -ly, or -ing.

my $example = "He is eating. She is running. They are playing in the bowl."

how can I use regular expressions to change $example to say:

"He is pudding. She is pudding. They are pudding in the bowl."

I thought that something like

$example =~ s/\s.*+ing/pudding/g;

would do it, but it's not working. What am I doing wrong?

  • Comment on Matching 'words' in a string based on a suffix

Replies are listed 'Best First'.
Re: Matching 'words' in a string based on a suffix
by mirod (Canon) on Feb 07, 2001 at 12:51 UTC

    The regexp you are looking for is:

    ~s/\w+ing\b/pudding/g

    for which japhy's YAPE::Regexp-Explain] gives the following explanation (reformated):

    The regular expression: /\w+ing\b/ matches as follows: NODE EXPLANATION ==== =========== \w+ word characters (a-z, A-Z, 0-9, _) (1 or more times) ing 'ing' \b the boundary between a word char (\w) and something that is not a word char

    If you want strings like f***ing to be replaced use \S (matches anything but a space) instead of \W.

    Your regexp does not compile, I guess you wanted to write something like /\S+ing/ which matches anything that's not spaces then ing but then strings like derringer (ing in the middle of the string) would be matched.

      it's true that the expression  /\S+ing/ would match  derringer
      but  /\S+ing$/ wouldn't...

      this expression would also work in the above required example, i believe...
        mirod just pointed out, the  $ in my previous reply should have been a  \b... thanks, mirod...
Re: Matching 'words' in a string based on a suffix
by mr.nick (Chaplain) on Feb 07, 2001 at 19:30 UTC
    You almost have your regular expression correct. The following worked as expected for me:
    $example=~s/\w+ing\b/pudding/g;
    I used \w for matching so that any grouping of "word characters" followed by "ing" are replaced.

    whoops! duplicated someone else's post :( And thanks to mirod for the "\b" correction.