Jump to content

Split String Based On Regex In Perl


Recommended Posts

Let's assume this is what I'm working with...


$string = 'xxxxxxxxyyyy';

$regex = 'xxxxxxxx';


And my goal is to have the following results...


$value1 = 'xxxxxxxx';

$value2 = 'yyyy'; (Remainder after $regex)


What commands am I using to get to that point?

I have used regex to remove and/or alter text, but

I have never used them to split apart a string.


I can hack around to get a result, but I prefer to

do it as 'properly' as possible and minimizing lines

and execution cycles.

Link to comment
Share on other sites

OK, looks like this should give you what you want.... I think :)


>$string = 'xxxxxxxxyyyy';
$regex = '/(xxxxxxxx)/';

$result = preg_split( $regex, $string, 2, PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE );

Edited by click
Link to comment
Share on other sites

$result = preg_split( $regex, $string, 2, PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE );[/code]


Except preg_split is a php function and he's using perl.


This is the way I'd probably do it, although there may be a better way (made up the regex to match on example string just to show):


>$string = 'xxxxxxxxyyyy';
$regex = '(x)+';

if ($string =~ m/$regex/) {
  $value1 = $&;

  $value2 = $string;
  $value2 =~ s/$regex//;


Result of that:

$value1 = 'xxxxxxxx'

$value2 = 'yyyy'


I'm not aware of a way to split the string up in a single operation within perl natively.

Link to comment
Share on other sites

Except preg_split is a php function and he's using perl.

hahaha I think that officially makes me a moron! :)


Sorry, I don't know how I managed to miss that. I guess the $ variables threw me into php mode (I haven't done any significant perl in a while). Maybe there should be some basic IQ test before we're allowed to post. :D I think the Perl split() works pretty much the same as preg_split(), though. Any part of the regex in parenthesis will be included in the result array.


Anyhow, I'm glad you figured it out.

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Create New...