Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

substitution eats space 1

Status
Not open for further replies.

facemann

Programmer
May 19, 2005
9
US
Hello all.

I am trying to remove unwanted commas from a CSV file. I am attempting to do this by changing any commas that are not contained in parenthesis to a colon character.
The following test program produces an unexpected result:
Code:
my $string = '"data","home 966-2815, cell 567-9832","data"';
print "string before sub = $string\n";
$string =~ s/[^"],[^"]/:/g;
print "string after sub = $string\n";

Outputs:

string before sub = "data","home 966-2815, cell 567-9832","data"
string after sub = "data","home 966-281:cell 567-9832","data"


I expected the only the comma after 964-2815 to be deleted but it also deleted the space following the comma. Why and how do I prevent that?

P.S.
The following substitutions also has the same output.
Code:
s/[^"],{1}[^"]/:/g;  ## and
s/[^"],{1}?[^"]/:/g;

Facemann
 
Ah, I just noticed that the substituion is eating a character on both sides of the comma!
Hmm....
 
Duh,

The substitution was including the surrounding characters.
The following code does the trick.
Code:
my $string = '"data","home 966-2815, cell 567-9832","data"';
print "string before sub = $string\n";
while($string =~ /[^"],[^"]/g){
  my $pos = pos($string);
  substr($string,$pos-2,1) = ':';
}
print "string after sub = $string\n";
 
wouldn't this do the same thing (in 1 line)?

Code:
$string =~ s/([^"]),([^"])/$1:$2/g;

it just puts the matching characters before and after the comma back where they belong. And you don't need a while loop :)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top