简体   繁体   中英

How to replace matched pattern in perl

I'm trying to write a Perl program that accepts an input pattern and print the string with the matched part enclosed with parentheses. For example, if I input the regex ".p" and the string is "developing", it should print "devel(op)ing"

Here is my program:

if (/($pattern)/) {
    $_ =~ s/$1/($1)/;
    print;
} else {
    print "no match\n";
}

When I run it, I got the error message:

Use of uninitialized value $1 in concatenation (.) or string at q1.pl line 12, <> line 1.

The string "devel()ing" was returned. I did some research and seems like the $1 is uninitialized because the string is not matched, but in my case, the $1 should always be initialized since I checked with "if...else..."

After the match, $1 contains the string op .

The substitution than matches the op , but there are no parentheses in the search part, so $1 gets cleared, and there's nothing to substitute the op with.

Add the parentheses to create the capture group again:

s/($1)/($1)/;

$1 in a replacement contains the first capture group in the match, but there are no capture groups in your regular expression. You can use $& to get everything matched by the regular expression.

s/$1/($&)/;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM