Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: Regex: Changing $1

by davido (Cardinal)
on Sep 04, 2013 at 15:11 UTC ( [id://1052369]=note: print w/replies, xml ) Need Help??


in reply to Regex: Changing $1

A one-liner using the in-place edit switch.

perl -pi.bak -e 's/^[^"]*"([^"]+?)"[^"]*$/$1/' filename

This reads in the line, and drops everything that comes before the first quote, or after the second. It will fail if the string contains more than one set of balanced quotes. It then writes the part that came between the quotes back out to the original file, and leaves a backup in place.

That's a slight lie, actually; If I recall -i.bak semantics, it renames the input file, and then writes a new file to the original input filename.

You can mimic that approach in long-hand code as well; open the input file, rename it to something else to save it just in case, open a new output file to the name of the old input file, read each line, drop the parts you don't want, write each line out to the output file, done.

But problems where you're matching text between quotes are seldom as simple as they seem at first. What if the string is, This is line 1 "Hello! I said, "Hello!""? Now you've got a problem. That problem is handled more easily using Text::Balanced.


Dave

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1052369]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (11)
As of 2024-04-18 14:15 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found