Perl 和元字符中的斜线和散列 [英] Slashes and hashes in Perl and metacharacters

查看:53
本文介绍了Perl 和元字符中的斜线和散列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

感谢大家之前的帮助!.我有一个关于 Perl 中的 RegExp 的查询

Thanks for the previous assistance everyone!. I have a query regarding RegExp in Perl

我的问题是..

我知道,匹配时您可以写 m//或//或 ##(如果您使用它,则必须包含 m 或 s).引起我困惑的是关于转义字符的书籍示例.我相信大多数人都会逃避很多字符,作为程序工作的一种可靠方式,不会丢失元字符,即:\@ 在电子邮件地址中匹配 @ 时说.

I know, when matching you can write m// or // or ## (must include m or s if you use this). What is causing me the confusion is a book example on escaping characters I have. I believe most people escape lots of characters, as a sure fire way of the program working without missing a metacharacter something ie: \@ when looking to match @ say in an email address.

这是我的问题,我知道这个脚本的作用:

Here's my issue and I know what this script does:

$date= "15/12/99"
$date=~ s#(\d+)/(\d+)/(\d+)#$1/$2/$3#; << why are no forward slashes escaped??
print($date);

然而,我后来的例子显示它被重写为(我也理解并且它们被转义了)

Yet the later example I have, shows it rewritten, as (which i also understand and they're escaped)

$date =~ s/()(\d+)\/(\d+)\/(d+)/$2\/$1\/$3; <<<<which is escaping the forward slashes.

我知道斜线或散列是程序员的偏好和使用.我不明白的是为什么第二个例子会避开斜线,而第一个例子却没有 - 我已经尝试过,而且它们是双向的.没有用散列转义斜线?更令人困惑的是,看看我之前也有的另一本书示例,再次使用哈希,它们也转义了 @ 符号.

I know the slashes or hashes are programmer preference and their use. What I don't understand is why the second example, escapes the slashes, yet the first doesn't - I have tried and they work both ways. No escaping slashes with hashes? What's even MORE confusing is, looking at yet another book example I also have earlier to this one, using hashes again, they too escape the @ symbol.

if ($address =~ m#\@#) { print("这是一个电子邮件地址");} 或类似的东西

那么不使用散列或斜杠的情况下,您如何逃避呢?我知道您必须转义元字符才能匹配它们,但我很困惑.

So what do you escape from what you don't using hashes or slashes? I know you have to escape metacharacters to match them but I'm confused.

推荐答案

当你构建一个正则表达式时,你定义一个字符作为正则表达式的分隔符,即执行 //##.
如果您需要在正则表达式中使用该字符,则需要对其进行转义,以便正则表达式引擎不会将其视为正则表达式的结尾.

When you build a regexp, you define a character as a delimiter for your regexp i.e. doing // or ##.
If you need to use that character inside your regexp, you will need to escape it so that the regexp engine does not see it as the end of the regexp.

如果在正斜杠 / 之间构建正则表达式,则需要对正则表达式中包含的正斜杠进行转义,因此在第二个示例中进行转义.

If you build your regexp between forward slashes /, you will need to escape the forward slashes contained in your regexp, hence the escaping in your second example.

当然,同样的规则适用于您用作正则表达式分隔符的任何字符,而不仅仅是正斜杠.

Of course, the same rule apply with any character you use as a regexp delimiter, not just forward slashes.

这篇关于Perl 和元字符中的斜线和散列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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