http://qs321.pair.com?node_id=11116857

anita2R has asked for the wisdom of the Perl Monks concerning the following question:

Greetings Monks,

I am trying to construct a regex to use in a split command.

The string to be split consists of from one to four comma separated fields. The second field can contain text which may use backslashes to escape non-separating commas '\,', the backslash itself '\\', and 2 character hex codes '\x2B' hex codes '\0x2B'. Here is an example:

$text = '1,Something\,\\text\\text\0x2B,X,99';

I can split this with a regex using a negative lookbehind:

my $regex = '(?<!\\\),'; split( /$regex/, "$text" );

so it splits on a comma unless it is preceded by a backslash.

Actual outcome:

1 Something\,\text\text\0x2B X 99

(In a terminal the double backslash appears as a single \, but this is not an issue as the split data is processed further in the perl script).

Now my problem:

If an escaped backslash comes before the next separating comma the regex 'sees' a backslash before the separating comma and does not split.

$text = '1,This is a problem->\\,B,2';

Actual output:

1 This is a problem->\,B 2

I have tried several regexe's based on the concept that there needs to be a match on a comma except when preceded by a backslash, using negative lookbehind OR there is a match on a comma when preceded by two backslashes using positive lookbehind. Here are two that I have tried

$regex = '(?<!\\\),|(?<=\\\\),';

$regex = '(?<!\\\),|(?<=[\\\]{2}),';

Neither gives the required output - so maybe I am lost in ever more escaped escaped escaped backslashes! I have tried variations with more backslashes in the positive lookbehind section of the regex. I also tried \Q...\E to avoid escaping the backslashes but this results in an error:'Unrecognized escape \Q passed through in regex'. I tried building the regex with qr like this

my $regex = qr /(?<!\\),|(?<=\\\\),/;

but it still didn't split on '\\,'.

As a test of my concept I replaced all backslashes with colons

my $regex = '(?<!:),|(?<=[:]{2}),'; my $text = '1,This:, is not a problem->::,B,2'; my @test = split( /$regex/, "$text" ); foreach( @test ) { print "$_\n"; }

The output was 'correct'

1 This:, is not a problem->:: B 2

In summary: I need to split a string at each comma or comma preceded by two backslashes but don't split at a comma preceded by only one backslash.

Any suggested approaches to this problem would be appreciated.