Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex: Split string on number/string?

Consider the following:

700italic
regular
300bold
300bold900

All of those are different examples, only one of the rows will be executed per time.

Expected outcome:

// 700italic
array(
    0 => 700
    1 => itailc
)

// regular
array(
    0 => regular
)

// 300bold
array(
    0 => 300
    1 => bold
)

// 300bold900
array(
    0 => 300
    1 => bold
    2 => 900
)

I made the following:

(\d*)(\w*)

But it's not enough. It kinda works when i only have two "parts" (number|string or string|number) but if i add a third "segment" to it i wont work.

Any suggestions?

like image 536
qwerty Avatar asked Dec 13 '12 15:12

qwerty


People also ask

How split a string in regex?

To split a string by a regular expression, pass a regex as a parameter to the split() method, e.g. str. split(/[,. \s]/) . The split method takes a string or regular expression and splits the string based on the provided separator, into an array of substrings.

How do you split a string and number in Python?

Use the re. split() method to split a string into text and number, e.g. my_list = re. split(r'(\d+)', my_str) .

Is split faster than regex?

Regex will work faster in execution, however Regex's compile time and setup time will be more in instance creation. But if you keep your regex object ready in the beginning, reusing same regex to do split will be faster.


3 Answers

You could use preg_split instead. Then you can use lookarounds that match a position between a word an a letter:

$result = preg_split('/(?<=\d)(?=[a-z])|(?<=[a-z])(?=\d)/i', $input);

Note that \w matches digits (and underscores), too, in addition to letters.

The alternative (using a matching function) is to use preg_match_all and match only digits or letters for every match:

preg_match_all('/\d+|[a-z]+/i', $input, $result);

Instead of captures you will now get a single match for every of the desired elements in the resulting array. But you only want the array in the end, so you don't really care where they come from.

like image 124
Martin Ender Avatar answered Oct 19 '22 14:10

Martin Ender


Could use the PREG_SPLIT_DELIM_CAPTURE flag.

Example:

<?php

$key= "group123425";
$pattern = "/(\d+)/";

$array = preg_split($pattern, $key, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
print_r($array);

?>

Check this post as well.

like image 33
SeanWM Avatar answered Oct 19 '22 15:10

SeanWM


You're looking for preg_split:

preg_split(
    '((\d+|\D+))', $subject, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY
)

Demo

Or preg_match_all:

preg_match_all('(\d+|\D+)', $test, $matches) && $matches = $matches[0];

Demo

like image 1
hakre Avatar answered Oct 19 '22 15:10

hakre