CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Regular Expressions:
Is there a way to use qq() or q() with replacement in regex?

 



poly4life
Novice

Mar 25, 2011, 9:30 AM

Post #1 of 4 (2427 views)
Is there a way to use qq() or q() with replacement in regex? Can't Post

Hello,

I hope my logic makes sense, here. I have a regex:

s~pattern~replacement~g

If I have to escape quotes or apostrophes, I'd normally do this:

s~foo~\'foo\'~g
or
s~foo~\"foo\"~g

This can become unpleasant looking with multiple escapes:

s~foo~\'foo\'\'bar\'\"foo\"\"bar\"~g

Is there some means where I can use something similar to qq(...) or q(...) to automatically escape the quotes and apostrophes? If you look at extended pattern modfiers like (?s) or /Q.../E, you can essentially enclose the pattern. I've never used something like /Q.../E for replacement, so I don't know if you can apply those modifiers to the replacement string. But I didn't see a modifier for quotes or apostrophes.

Essentially, I want the regex expression to look like this:

s~foo~qq(bar)q(bar)~g, which would be equivalent to s~foo~\"bar\"\'bar\'~g.

I would appreciate any help. Thank you.


FishMonger
Veteran / Moderator

Mar 25, 2011, 9:47 AM

Post #2 of 4 (2425 views)
Re: [poly4life] Is there a way to use qq() or q() with replacement in regex? [In reply to] Can't Post

The single and double quote characters are not regex metacharacters, so there's no need to escape them.


poly4life
Novice

Mar 25, 2011, 10:26 AM

Post #3 of 4 (2420 views)
Re: [FishMonger] Is there a way to use qq() or q() with replacement in regex? [In reply to] Can't Post

That is correct, if I'm running it from a script.

i.e.

Code
#!/usr/local/bin/perl -i.bak 

while(<>) {
s~test~"bar"'bar'bar~g;
print;
}


But if I'm running in single-line edit mode, i.e.


Code
perl -pi.bak -e "s~bar~\"bar\"'bar'bar~g" test.txt


I need to escape the quotes, because it's enclosed with the expression after -e is enclosed in quotes. I suppose this is not a regex issue but a general Perl issue. In this case, I imagine I must escape quotes with slashes.

Thank you for your help.


FishMonger
Veteran / Moderator

Mar 25, 2011, 10:48 AM

Post #4 of 4 (2416 views)
Re: [poly4life] Is there a way to use qq() or q() with replacement in regex? [In reply to] Can't Post

It's not really a Perl issue, it's a shell issue, or in this case cmd.exe

Escaping the double quotes is the easiest, assuming you actually need to use double quotes instead if single quotes. Or, you could use the corresponding octal number for the double quotes.

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives