Reputation: 133
Given the following line:
rebeka mecsek:/export/home5/users/rebeka;
I'd like to get only the word "mecsek" from the line. There is a space between the word "rebeka" and "mecsek", and the line beginning with no space.
I tried the following:
$homeserver=~s/.*\s//;
But I don't want the colon or the part following it, only the word "mecsek".
Could anybody help me?
Thank you very much!
Upvotes: 2
Views: 1766
Reputation: 139531
Remember Randal’s rule:
Randal Schwartz (author of Learning Perl) says:
Use capturing or
m//g
when you know what you want to keep.
Usesplit
when you know what you want to throw away.
You know what you want to keep, but you haven’t told us everything you know. Do you want the run of word characters following the first space in the line?
print $1, "\n" if $homeserver =~ / (\w+)/;
Do you want to keep the longest, leftmost string of word characters before :/
, wherever that happens to be?
print $1, "\n" if $homeserver =~ /(\w+):\//;
Can we depend on rebeka being at the beginning of the string?
print $1, "\n" if $homeserver =~ /^rebeka (\w+)/;
If not, is it safe to assume that the beginning of the string will be some contiguous run of word characters?
print $1, "\n" if $homeserver =~ /^\w+ (\w+)/;
When matching with regular expressions, define your anchors: the features you can rely on being present in the text as markers or bookends for what you want to keep. Also note that the above examples use $1
inside a conditional only; never use capture variables unconditionally.
Upvotes: 4
Reputation: 12940
I vote for the pattern /(?<=\S\s)([^\s:][^:]*):/
and the result is in $1
.
Upvotes: 0