lwillems
lwillems

Reputation: 103

Exclude regex assertion from result?

I am trying to extract a part of text (book reference) from products description in a large database

Example :

books A 41.14 (products -> cat1 -> (1990-2000))

I only need the A 41.14

I have tried this in PHP (always followed by parentheses)

books(.*)(?=\s\(.*\))

but it does not capture as expected, i need to exclude assertion, is it possible?

Upvotes: 0

Views: 57

Answers (4)

Vadimas Sizikovas
Vadimas Sizikovas

Reputation: 74

If wou always have one letter before float you can use.

(\w (\d+)\.(\d+))

Upvotes: 0

Avinash Raj
Avinash Raj

Reputation: 174796

Use \K in your regex to exclude the previous matches and also use lookaheads to check what's following should be \s*( (ie, zero or more spaces followed by a ( symbol)

books\s*\K.*?(?=\s*\()

DEMO

PHP code would be,

<?php
$mystring = "books A 41.14 (products -> cat1 -> (1990-2000))";
$regex = '~books\s*\K.*?(?=\s*\()~';
if (preg_match($regex, $mystring, $m)) {
    $yourmatch = $m[0]; 
    echo $yourmatch;
    }
?> //=> A 41.14

Upvotes: 1

plmarcelo
plmarcelo

Reputation: 373

Please, try this:

preg_match( '/books\s?([\w]+\s?[\d|\.]+).*/i', "books A 41.14 (products -> cat1 -> (1990-2000))", $matches);
echo $matches[1];

Hope it helps,

Best Regards

Upvotes: 0

Bobulous
Bobulous

Reputation: 13169

If the product code which interests you can never include the open parenthesis character then you could simply use this pattern:

books\s+([^(]+)\s+\(

If the open parenthesis character can appear in the product code then your task is trickier.

Upvotes: 0

Related Questions