Connecting Tech Pros Worldwide Help | Site Map

Need Help (Regular Expressions)

Newbie
 
Join Date: Sep 2006
Posts: 2
#1: Sep 26 '06
hi

I've a got a problem
i must split a string (the split separator is a space)

Issue : spaces that should be taken into account are those which are not between quotes (")

example
$ligne = 0126878 "my name" "my_name_without_space" 12356 "a b c d e" "f g h i j"

after the split into @var, the result should be
$var[0] = 0126878
$var[1] = "my name"
$var[2] = "my_name_whithout_space"
$var[3] = 12356
$var[4] = "a b c d e"
$var[5] = "f g h i j"

i tried a lot of regexp but i'm a little bit confused at this point and can't get none of them working

if someone could help me, that would be great !

thanks
thurban's Avatar
Newbie
 
Join Date: Sep 2006
Posts: 6
#2: Sep 29 '06

re: Need Help (Regular Expressions)


I know it's not very cool, but the following solution should work:

Expand|Select|Wrap|Line Numbers
  1. my $line = '0126878 "my name" "my_name_without_space" 12356 "a b c d e" "f g h i j"';
  2.  
  3. # get the number in the format "0126878"
  4. $line =~ s/(\d+)/\"\1\"/ig;
  5.  
  6. # replace the space " " separating the data with a ";"
  7. $line =~ s/\"\s\"/\";\"/ig;
  8.  
  9. # now remove all of the "
  10. $line =~ s/\"//ig;
  11.  
  12. # the line looks like this now:
  13. # 0126878;my name;my_name_without_space;12356;a b c d e;f g h i j
  14.  
  15.  
  16. # split it by the ;
  17. my @var = split/;/,$line;
  18.  
  19.  
Newbie
 
Join Date: Sep 2006
Posts: 2
#3: Sep 30 '06

re: Need Help (Regular Expressions)


thanks for the reply, but meanwhile i found the solution

my @var = ($ligne =~ m/("[^"]+"|\S+)/g);
Reply