Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
995 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...