in reply to Re: Capturing the nth word in a string
in thread Capturing the nth word in a string

Nice. Tiny changes, though... want nth char, not (n+1)th... also, you want \s+, not \s*... and might as well decide that by "word" we mean a run of non-whitespace (that is... probably a bad idea to mix \w and \S... so I'll just go with \S).
[me@host bin]$ perl -we '$n = $ARGV[0]; $_ = "a b csadf sdfas ddd"; /( +?:\S+\s+){@{[$n-1]}}(\S+)/; print "$1\n"' 1 a [me@host bin]$ perl -we '$n = $ARGV[0]; $_ = "a b csadf sdfas ddd"; /( +?:\S+\s+){@{[$n-1]}}(\S+)/; print "$1\n"' 2 b [me@host bin]$ perl -we '$n = $ARGV[0]; $_ = "a b csadf sdfas ddd"; /( +?:\S+\s+){@{[$n-1]}}(\S+)/; print "$1\n"' 4 sdfas [me@host bin]$

------------
:Wq
Not an editor command: Wq

Replies are listed 'Best First'.
Re: Re: Re: Capturing the nth word in a string
by pg (Canon) on Oct 14, 2003 at 05:16 UTC
    The reason I used \s* not \s+ is, to make it also work for the last word, as there is no space after that one.
      I think you misunderstand... \s not the same as \S.

      ------------
      :Wq
      Not an editor command: Wq