in reply to Needing to take out 3rd word of sting

There is, of course, more than one way to do it, and those ways are highly dependant on what you consider to be a word. If you are content with the \w description of word, you can use the following example. You will have to modify that example if you have a more specific description of word (such as needing words to contain hyphens, apostraphes, accent characters, etc.).

You can remove the {n}th+1 word like this:

my $string = "one two three four"; $string =~ s/^((?:\w+\s+){2})(\w+)\s+\b/$1/; my $word = $2; print "$string, $word\n";

That should be enough ammunition for you to see how to put it back as well, but if not:

$string =~ s/((?:\w+\s+){2})/$1$word /;

This method has some shortcomings. One of them is that if your words are not space-delimited, you will end up with trouble. Also if your phrase of words contains punctuation, such as a comma or a period, that will also wreck havoc. But you didn't specify such details in the description of your problem. Ask the question filled with ambiguity and vagueness, you get an answer that may not solve your problem. Note that I put the space following the word back into the string. It's somewhat hard to see, but it's right after $word and before /;

A few days ago you started a similar thread, take out section of a string then put it back. You received several good answers. In this response you were advised to read the perlre perldoc page. Had you done this, you would have already known the answer to today's question. To that reading assignment I would also add perlretut and perlrequick. In fact, reverse that order, read perlrequick, perlretut, and perlre in that order. At some point through that reading the regular expression light-bulb will flick on in your mind.

I hope this advice helps ease the pain of diving into something new, and admittedly, somewhat overwhelming at first.

Dave

"If I had my life to do over again, I'd be a plumber." -- Albert Einstein

Replies are listed 'Best First'.
Re: Re: Needing to take out 3rd word of sting
by mr_evans2u (Novice) on Sep 24, 2003 at 21:49 UTC
    I hope it flicks on soon, I'm still very new to all of the regular expressions coding and it is driving me nuts. By the way I did get the other question to work, had to mess with it some but did get it. Thanks
Re: Re: Needing to take out 3rd word of sting
by Anonymous Monk on Sep 24, 2003 at 20:03 UTC
    Here is an example of what I'm considering a word:
    /\b(?:impotence(?:problem|cure|solution)|Premature Ejaculation|erectile dysfunction)/i
    It has various characters and I guess it does have whitespace. So it would need to be the third and any other after that
      Sorry didn't log in. Here is an example of what I'm considering a word:
      /\b(?:impotence(?:problem|cure|solution)|Premature Ejaculation|erectile dysfunction)/i
      It has various characters and I guess it does have whitespace. So it would need to be the third and any other after that