简体   繁体   中英

Perl string replace: Match, but not replace, part of regex

Say I have a string in Perl I am trying to match and replace with stuff:

$string =~ s/[^a-zA-Z]$find[^a-zA-Z]/$replace/g;

So as shown, I want to replace everything that is surrounded on both sides by nonletter characters. However, when I replace the string, I do NOT want to also replace these characters: they are just necessary for correct matching. How can I tell the Perl regex to avoid replacing the things surrounding $find ?

将它们存储为匹配的组,并在替换字符串中引用它们:

$string =~ s/([^a-z])$find([^A-Z])/\1$replace\2/gi;

使用环顾断言

s/(?<=[^a-zA-Z])$find(?=[^a-zA-Z])/$replace/g

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