fionbarr has asked for the wisdom of the Perl Monks concerning the following question:

I have a string that looks like:
wppwd01a0099_NET_basp_virtual_adapter
I want to capture the chars before the first '_' but what I end up with is:
wppwd01a0099_NET_basp_virtual
The regular expression I'm trying is:
if ( $this_server =~ m/^(\w+)_/ ) { $this_server = $1; }
what am I doing wrong?

Replies are listed 'Best First'.
Re: minimal match regular expression
by toolic (Bishop) on Mar 03, 2015 at 16:34 UTC
    You can use s/// to remove everything after the 1st underscore (inclusive):
    use warnings; use strict; my $this_server = 'wppwd01a0099_NET_basp_virtual_adapter'; $this_server =~ s/_.*//; print "$this_server\n"; __END__ wppwd01a0099
      bravo, thanks
        you can also:
        use warnings; use strict; my $match, $pruned = split(/_/, $_); print $match
        at work so cant* test it haha
      thanks...this is the one I ended up with after finding out I had some occurances of an internal '-' which choked on (\w+?)
Re: minimal match regulara expression
by trippledubs (Deacon) on Mar 03, 2015 at 17:19 UTC
    You can also use a negated character class to match everything except what you don't want
    my ($match) = 'wppwd01a0099_NET_basp_virtual_adapter' =~ /^([^_]*)/; print $match; #wppwd01a0099
Re: minimal match regulara expression
by Laurent_R (Canon) on Mar 03, 2015 at 18:06 UTC
    Hi, the problem with your regex:
    if ( $this_server =~ m/^(\w+)_/ ) { $this_server = $1; }
    is greedy matching: the expression tries to capture as much as possible until the last "_". Try to change it to a non greedy quantifier (+? instead of +:
    if ( $this_server =~ m/^(\w+?)_/ ) { $this_server = $1; }
    Update: Oops, I had not noticed that you actually had found the same solution by yourself (your second post), in part due to the fact that is is poorly formated. BTW, for a closing format tag, you should use a forward slash, not a back slash.

    Je suis Charlie.
Re: minimal match regulara expression
by fionbarr (Friar) on Mar 03, 2015 at 16:19 UTC
    got it: # remove everything after underscore_ 259 if ( $this_server =~ m/^(\w+?)_/ ) { 260 $this_server = $1; 261 }