如何向带引号的正则 (qr) 表达式添加修饰符

发布于 2024-12-14 11:32:47 字数 266 浏览 3 评论 0原文

有没有一种简单的方法可以将正则表达式修饰符(例如“i”)添加到带引号的正则表达式中?例如:

$pat = qr/F(o+)B(a+)r/;
$newpat = $pat . 'i'; # This doesn't work

我能想到的唯一方法是 print "$pat\n" 并返回 (?-xism:F(o+)B(a+)r) 并尝试使用替换删除 ?-xism: 中的“i”

Is there an easy way to add regex modifiers such as 'i' to a quoted regular expression? For example:

$pat = qr/F(o+)B(a+)r/;
$newpat = $pat . 'i'; # This doesn't work

The only way I can think of is to print "$pat\n" and get back (?-xism:F(o+)B(a+)r) and try to remove the 'i' in ?-xism: with a substitution

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

可爱暴击 2024-12-21 11:32:47

您不能将该标志放入已有的 qr 结果中,因为它受到保护。相反,使用这个:

$pat = qr/F(o+)B(a+)r/i;

You cannot put the flag inside the result of qr that you already have, because it’s protected. Instead, use this:

$pat = qr/F(o+)B(a+)r/i;
最冷一天 2024-12-21 11:32:47

您可以修改现有的正则表达式,就像它是一个字符串一样,只要您之后重新编译它

  my $pat = qr/F(o+)B(a+)r/;
  print $pat, "\n";
  print 'FOOBAR' =~ $pat ? "match\n" : "mismatch\n";

  $pat =~ s/i//;
  $pat = qr/(?i)$pat/;
  print $pat, "\n";
  print 'FOOBAR' =~ $pat ? "match\n" : "mismatch\n";

OUTPUT

  (?-xism:F(o+)B(a+)r)
  mismatch
  (?-xism:(?i)(?-xsm:F(o+)B(a+)r))
  match

You can modify an existing regex as if it was a string as long as you recompile it afterwards

  my $pat = qr/F(o+)B(a+)r/;
  print $pat, "\n";
  print 'FOOBAR' =~ $pat ? "match\n" : "mismatch\n";

  $pat =~ s/i//;
  $pat = qr/(?i)$pat/;
  print $pat, "\n";
  print 'FOOBAR' =~ $pat ? "match\n" : "mismatch\n";

OUTPUT

  (?-xism:F(o+)B(a+)r)
  mismatch
  (?-xism:(?i)(?-xsm:F(o+)B(a+)r))
  match
童话里做英雄 2024-12-21 11:32:47

看起来唯一的方法是对 RE 进行字符串化,用 (i-) 替换 (-i) 并重新引用它:

my $pat = qr/F(o+)B(a+)r/;
my $str = "$pat";
$str =~ s/(?<!\\)(\(\?\w*)-([^i:]*)i([^i:]*):/$1i-$2$3:/g;
$pati = qr/$str/; 

更新:perl 5.14 在 不同的方式,所以我的示例应该看起来像

my $pat = qr/F(o+)B(a+)r/;
my $str = "$pat";
$str =~ s/(?<!\\)\(\?\^/(?^i/g;
$pati = qr/$str/;

但是我手头没有 perl 5.14,无法测试它。

UPD2:我也未能检查转义的左括号。

Looks like the only way is to stringify the RE, replace (-i) with (i-) and re-quote it back:

my $pat = qr/F(o+)B(a+)r/;
my $str = "$pat";
$str =~ s/(?<!\\)(\(\?\w*)-([^i:]*)i([^i:]*):/$1i-$2$3:/g;
$pati = qr/$str/; 

UPDATE: perl 5.14 quotes regexps in a different way, so my sample should probably look like

my $pat = qr/F(o+)B(a+)r/;
my $str = "$pat";
$str =~ s/(?<!\\)\(\?\^/(?^i/g;
$pati = qr/$str/;

But I don't have perl 5.14 at hand and can't test it.

UPD2: I also failed to check for escaped opening parenthesis.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文