Regular Expression newbie help/question

S

Sven

Hi,
I need some assistance on a search and replace issue with a
commaseparated file.
I need to replace all commas(,) on every lines EXCEPT those that occur
within doublequotes (",")

Thanks,

Sven
 
G

Greg Bacon

: I need some assistance on a search and replace issue with a
: commaseparated file.
: I need to replace all commas(,) on every lines EXCEPT those that occur
: within doublequotes (",")

If you want to roll your own:

$ cat try
#! /usr/local/bin/perl

use warnings;
use strict;

while (<DATA>) {
s/(".*?"|,)/$1 eq ',' ? '<=>' : $1/eg;
print;
}

__DATA__
"foo,bar"
foo,bar
foo,bar,"baz,quux"
foo,,bar,"baz,quux"
foo,bar,,"baz,,quux"

$ ./try
"foo,bar"
foo<=>bar
foo<=>bar<=>"baz,quux"
foo<=><=>bar<=>"baz,quux"
foo<=>bar<=><=>"baz,,quux"

Consider using Text::CSV_XS, available on the CPAN.

Greg
 
T

Tad McClellan

Sven said:
I need to replace all commas(,) on every lines EXCEPT those that occur ^^^^^^
within doublequotes (",")


perldoc -q EXCEPT

How can I split a [character] delimited string except when inside
[character]? (Comma-separated files)


You are expected to check the Perl FAQ before posting to the
Perl newsgroup.

After you get the fields split, use join() to put them back
together with some other separator.

Or, better yet, use a module that understands the CSV format.

http://search.cpan.org/search?query=CSV&mode=all
 
G

Gunnar Hjalmarsson

Sven said:
I need some assistance on a search and replace issue with a
commaseparated file.
I need to replace all commas(,) on every lines EXCEPT those that
occur within doublequotes (",")

s/("[^"]*")|,/$1 ? $1 : $replacement/eg;
 
E

Eric J. Roode

(e-mail address removed) (Sven) wrote in @posting.google.com:
Hi,
I need some assistance on a search and replace issue with a
commaseparated file.
I need to replace all commas(,) on every lines EXCEPT those that occur
within doublequotes (",")

Please read the FAQ before posting. Thanks.
 
H

Helgi Briem

(e-mail address removed) (Sven) wrote in @posting.google.com:


Please read the FAQ before posting. Thanks.

While I will usually be the first one to recommend
reading the documentation, the least you could do
is point the OP to the relevant bit of documentation
as it is far from easy to find.

"How can I split a [character] delimited string except
when inside [character]?"

The relevant section is in perlfaq4 and can be read
either by browsing through that document:

perldoc perlfaq4

or, searching for it within the perlfaq documents:

perldoc -q split

or

perldoc -q delimited
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top