使用变量作为 RegEx 模式 [英] Use variable as RegEx pattern

查看:38
本文介绍了使用变量作为 RegEx 模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用一个变量作为匹配文件名的 RegEx 模式:

I'd like to use a variable as a RegEx pattern for matching filenames:

my $file = "test~";
my $regex1 = '^.+\Q~\E$';
my $regex2 = '^.+\\Q~\\E$';
print int($file =~ m/$regex1/)."\n";
print int($file =~ m/$regex2/)."\n";
print int($file =~ m/^.+\Q~\E$/)."\n";

结果(或在 ideone.com 上):

0
0
1

谁能向我解释如何将变量用作 RegEx 模式?

Can anyone explain to me how I can use a variable as a RegEx pattern?

推荐答案

不能在单引号/非插值字符串中使用 \Q.词法分析器必须看到它.

You cannot use \Q in a single-quoted / non-interpolated string. It must be seen by the lexer.

无论如何,波浪号不是元字符.

Anyway, tilde isn’t a meta-character.

添加use regex "debug",你会看到实际发生的事情.

Add use regex "debug" and you will see what is actually happening.

这篇关于使用变量作为 RegEx 模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆