简体   繁体   English

Perl正则表达式动态捕获

[英]perl regex dynamic capturing

Is there a way to set a dynamic capture unit 有没有办法设置动态捕获单元

my $pattern = '`(.*?)`';
$string =~ s{$pattern}{<code/>$1</code>}im;

But instead of passing <code/>$1</code> directly to replace, i want to store it as a variable (which may defer depending on the type of data i want to capture) 但是我没有直接传递<code/>$1</code>进行替换,而是希望将其存储为变量(根据我要捕获的数据类型而定)

my $pattern = '`(.*?)`';
my $replace = '<code/>$1</code>'; #or my $replace = '<code/>$2</code>'
$string =~ s{$pattern}{$replace}im;

In this post , Jenda offers a solution that may be applicable to your case. 本文中 ,Jenda提供了可能适用于您的案例的解决方案。 It involves creating a sub and then evaluating the sub to a regex. 它涉及创建子项,然后将子项评估为正则表达式。

#!/usr/bin/perl
use strict;
use warnings;

my $pattern = '`(.*?)`';
my $replace = '<code/>$1</code>';
my $code = 'sub {$_[0] =~ s{$pattern}{'. $replace . '}ig}';
my $re = eval $code;

my $string = "Here `is` a string";
$re->($string);

print $string;

This prints Here <code/>is</code> a string Here <code/>is</code> a string打印Here <code/>is</code> a string

Hope this is helpful. 希望这会有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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