pfeds
pfeds

Reputation: 2273

Regex to extract 2 groups of words delimited by multiple spaces

Sorry, but stuck with this one...

I have a line that contains a key on the left and value on the right, with a number of spaces inbetween.

For example (I've had to use '_' to represent ' ' as Stackoverflow trims multiple spaces):

PRODUCT NAME________________________________Super 4HP Mower

PRODUCT MANUFACTURER_______________________________Honda

A key or value can match any set of letters, numbers, and characters such as ",',: etc.

How can I create a regex to extract the key and value separately?

Upvotes: 1

Views: 113

Answers (1)

Avinash Raj
Avinash Raj

Reputation: 174874

\s{2,} matches two or more spaces.

^(.*?)\s{2,}(.*)$

So the first (.*?) captures any number of characters until a double space is reached. \s{2,} matches two or more in-between spaces greedily. Then the next capturing group (.*) captures the value part. Just grab the key part from group index 1 and value part from group index 2.

DEMO

In php, you could do like

$txt = <<<EOT
PRODUCT NAME Super            4HP Mower
PRODUCT MANUFACTURER           Honda
EOT;
preg_match_all('~^(.*?)\s{2,}(.*)$~m', $txt, $match);
print_r($match[1]);
print_r($match[2]);

Output:

Array
(
    [0] => PRODUCT NAME Super
    [1] => PRODUCT MANUFACTURER
)
Array
(
    [0] => 4HP Mower
    [1] => Honda
)

Upvotes: 2

Related Questions