简体   繁体   中英

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?

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

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.

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

如果您在浮动之前始终只有一个字母,则可以使用。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM