Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

perl regex escape characters

Tags:

regex

perl

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?

like image 751
freshWoWer Avatar asked Dec 12 '22 17:12

freshWoWer


2 Answers

If you're using perl you don't have to use / as the regex delimiter if you preceed the delimiter with "m" for the matching operator, or "s" for the substitution operator (e.g. you can use # or ! or even any balanced parentheses/brackets: s[this][that]), and then you don't have to escape /. You can also use the quotemeta function or \Q\E regex escape sequences that automatically escape any metacharacters.

like image 181
runrig Avatar answered Jan 05 '23 11:01

runrig


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

like image 33
moinudin Avatar answered Jan 05 '23 10:01

moinudin