Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

regex - Slashes and hashes in Perl and metacharacters

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

My issue is..

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("That's an email address"); } or something similar

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...