Perl regex escape characters

I heard that perl is a good language when creating a regex, but I'm a little confused about characters requiring escaping

I checked the code 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'm not quite sure how to translate this to perl code

I tried,

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

and

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

and both refused

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

+4
source share
2 answers

You can use ! instead of / to surround your regular expression so that you cannot escape / .

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

must work. Here it is in action: http://ideone.com/TDrBG

+5
source

If you use perl, you do not need to use / as a regex separator if you go to the separator with "m" for the match operator or "s" for the replacement operator (for example, you can use # or ! Or even any balanced parentheses / brackets: s[this][that] ), and then you do not need to run / . You can also use the quotemeta function or \Q ... \E regex escape sequences that automatically remove any metacharacters.

+8
source

Source: https://habr.com/ru/post/1333619/


All Articles