Freddiboy
Freddiboy

Reputation: 133

Regex - How can I extract a string between two different strings?

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

Answers (4)

Greg Bacon
Greg Bacon

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.
Use split 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

hochl
hochl

Reputation: 12940

I vote for the pattern /(?<=\S\s)([^\s:][^:]*):/ and the result is in $1.

Upvotes: 0

Toto
Toto

Reputation: 91428

How about:

$homeserver =~ s/^\S*\s(\S+):.*$/$1/;

Upvotes: 2

ckruse
ckruse

Reputation: 9740

You need to match the whole line then:

s/[^\s]+ ([^\s+]):.*/$1/

Upvotes: 0

Related Questions