Sunday, February 3, 2008

Haskell-snippet: Split with regex

The first listing shows perl code for splitting a string with a delimiter "::|".

Listing 2.3.2008.1:

#!/usr/bin/perl
# Simple example, show regex split usage
print "Running\n";
$string = "file:///home/baby ::| test1::| test2";
$string2 = "file:///home/baby , test1, test2";
my @data = split /\s*::\|\s*/, $string;
print "----\n";
print join("", @data);
print "\n----\n";
print "Done\n";


The second listing below shows a haskell regex approach for performing the same operation:

Listing 2.3.2008.2:

import Text.Regex (splitRegex, mkRegex)

csv string = "abc ::| 123 ::|"

let csv_lst = splitRegex (mkRegex "\\s*(::\\|)+\\s*") csv
linkUrlField = (csv_lst !! 0) ...


End of code snippet.

No comments: