Perl Regex expression to capture string between start and end of line (with end of line having a space with character)

Viewed 409

My string of data is this:

(wlc-nyhy30-a) *

I need to strip off the beginning parenthesis and the end parenthesis that matches exactly ) *.

My end string should be:

wlc-nyhy30-a

I can easily strip off the beginning ( like below, but I'm having a very hard time getting Perl to match and remove end of line ) *

Here is the first part that works:

$output{'prompt'} =~ s/^\(//;

Appreciate any help. Thanks in advance.

1 Answers

You could use:

s/^\((.*)\)\s\*$/$1/

Explanation:

^          beginning of the string
\(         opening parenthese - needs to be escaped with \
(.*)       ...a capturing group...
\)         closing parenthese - needs to be escaped with \
\s         a single space
\*         a star - needs to be escaped
$          end of the string

This matches the string as a whole, hence it will apply on the example you provided as an example ((wlc-nyhy30-a) *), while also leaving untouched other strings such as (wlc-nyhy30-a) a.

Demo:

my $string = "(wlc-nyhy30-a) *";
$string =~ s/^\((.*)\)\s\*$/$1/
print $string, "\n";

Yields:

wlc-nyhy30-a
Related