tags:

views:

79

answers:

2

I have a string that I need to split on a certain character. However, I only need to split the string on one of those characters when it is flanked by digits. That same character exists in other places in the string, but would be flanked by a letter -- at least on one side. I have tried to use the split function as follows (using "x" as the character in question):

my @array = split /\dx\d/, $string;

This function, however, removes the "x" and flanking digits. I would like to retain the digits if possible. Any ideas?

+13  A: 

Use zero-width assertions:

my @array = split /(?<=\d)x(?=\d)/, $string;

This will match an x that is preceded and followed by a digit, but doesn't consume the digits themselves.

Marcelo Cantos
Perfect, thanks!
indiguy
Marcelo, would this match x at the beginning/end of a string?
DVK
@DVK: No, because that instance of `x` wouldn't be preceded by a digit. You could achieve this via negative assertions (to match `x` at the start and end of the string): `/(?<!\D)x(?!\D)/` but it wouldn't match the stated problem, of course.
Marcelo Cantos
@Marcelo - I'm not certain... without explicit clarification by OP I'm at least somewhat of a mind to consider "^x3" to be a valid separator... but you're probably right.
DVK
@DVK: The OP's phrase was "flanked by digits". I suppose you could argue that in `"x123"`, the `x` is flanked by digits, but that's a stretch.
Marcelo Cantos
A: 

You could first replace the character you want to split on with something unique, and then split on that unique thing, something like this:

$string =~ s/(\d)x(\d)/\1foobar\2/g;
my @array = split /foobar/, $string;
Brian