perl regex : surround tabbed numeric field by double quotes

T

toralf

I've a file containing tab separated values - most, but not all are
quoted - and now I'm wondering how to substitute a non-quoted value like
<tab>20090807<tab> by sth. like <tab>"20090807"<tab>
 
S

sln

I've a file containing tab separated values - most, but not all are
quoted - and now I'm wondering how to substitute a non-quoted value like
<tab>20090807<tab> by sth. like <tab>"20090807"<tab>

You would have to do some complicated regex (possibly multiple regx's),
but that depends on the data sample in regards to quote's, newlines, or other
shapes it can have.
A simple way is to split on tab, fix up the value, the join it back together.
Its ugly though.

-sln
------------
use strict;
use warnings;

my @ar = (
qq{\n12345145\t\n36367\t"qfqqbv"\n\t"0987"\t"asdf"a"\n },
qq{\t"01234"\taaaa\t494848\t}
);

for my $str (@ar) {
my $newstring = join "<tab>", map {/^(\s*|)"*(.*?|)"*(\s*|)$/; $1.'"'.$2.'"'.$3 } split (/\t/,$str);
print "-> $newstring\n\n";
}
__END__
 
S

sln

On Wed, 09 Sep 2009 12:09:05 -0700 in comp.lang.perl.misc,
(e-mail address removed) wrote,


Just in case \s* fails to match the empty string, eh?

Doh, what was I thinking.
/^(\s*)"*(.*?)"*(\s*)$/

-sln
 
S

sln

Errr, that matches *every* string...

Go figure, thats what I want...

my $newstring = join "<tab>", map {/^(\s*|)"*(.*?|)"*(\s*|)$/; $1.'"'.$2.'"'.$3 } split (/\t/,$str);

-sln
 
S

sln

Go figure, thats what I want...

my $newstring = join "<tab>", map {/^(\s*|)"*(.*?|)"*(\s*|)$/; $1.'"'.$2.'"'.$3 } split (/\t/,$str);
/^(\s*)"*(.*?)"*(\s*)$/
Its not perfect, but it's a start for somebody.

-sln
 
T

toralf

toralf said:
I've a file containing tab separated values - most, but not all are
quoted - and now I'm wondering how to substitute a non-quoted value like
<tab>20090807<tab> by sth. like <tab>"20090807"<tab>

Thx all - this works for me :

$s =~ s/\t\d{8}\t/\t"$&"\t/;
 

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