regexperl

perl regex escape characters


I have heard perl is a good language at doing regex but I am a bit confused at the characters that requires escaping.

I tested the code on http://regexlib.com/RETester.aspx and got the result I want

//home/dev/abc/code/hello/world.cpp#1
//home/dev/((.*?)/[^/]+).*#

Match   $1  $2
//home/dev/abc/code/hello/world.cpp#    abc/code    abc

However, I am not quite sure how do i translate this to perl code

I tried,

\/\/home\/dev\/\(\(\.\*\?\)\/\[\^\/\]\+\)\.\*\#

and

\/\/home\/dev\/((.*?)\/[^\/]+).*\#

and both failed

Don't you think the escaping makes the regex very unreadable? Am I using something wrong?


Solution

  • You can choose use ! instead of / to surround your regular expression so that you don't have to escape the /.

    m!//home/dev/((.*?)/[^/]+).*#!
    

    should work. Here's it in action: http://ideone.com/TDrBG