[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: tonight's meeting
Jay Link said:
> Since you might not make it tonight, how about giving us all another
> Perl regex lesson? :-)
Sure, why not.
> The following construction takes the second word in a string from
> <STDIN> and makes it the entirety of the string. It works, but I only half
> understand it.
>
> $_ =~ s/^([^ ]+) +([^ ]+).*/$2/;
OK, first of all, "$_ =~" is not necessary. s/// operates on $_ by
default.
Next, here's how I'd probably write that:
s/^(\S+)\s+(\S+).*$/$2/;
Since "[^ ]" means "not a space", in perl you may as well use \S,
which means "not a whitespace character", since that's probably what
you really mean. Ditto for "\s" instead of " " ("whitespace
character" instead of a literal space). So, here's what the left-hand
side breaks down to:
^ anchor at the beginning of the line/string
(\S+) one or more ("+") non-whitespace characters("\S"), assign
it to $1 since it is the first grouped expression (in
parentheses)
\s+ one or more whitespace characters ("\s")
(\S+) assign the next series of one or more non-whitespace
characters to $2
.* everything else (literally any number ("*") of any
character ("."))
$ anchor at the end of the line/string
Of course, the right-hand side replaces all of that with whatever is
in $2.
Steve
--
steve@silug.org | Southern Illinois Linux Users Group
(618)398-7320 | See web site for meeting details.
Steven Pritchard | http://www.silug.org/
-
To unsubscribe, send email to majordomo@luci.org with
"unsubscribe luci-discuss" in the body.