Jenz
Jenz

Reputation: 8369

Regex to match number not preceeded by alphabets

I want to get first number from the string before the word 'minimum', preceeded by a space and not succeeded by '-'. Example:

I'm trying with the following code:

$str = "Red  QQ-4555 White  TT-789 Yellow Minimum order applies. This is a test";
$explodeByMinimumArray = preg_split("/minimum/i", str_replace(array( '(', ')' ), ' ', $str));   
preg_match_all('/\d+(?!-\d)/', $explodeByMinimumArray[0], $numberFromStringBeforeMinimumArray);  
print_r($numberFromStringBeforeMinimumArray);

This is returning $numberFromStringBeforeMinimumArray as:

Array
(
    [0] => Array
        (
            [0] => 4555 
            [1] => 789
        )

)

But the expected output is empty as QQ-4555 and TT-789 are preceeded by some characters.

Can anyone help me to fix this? Thanks in advance.

Upvotes: 1

Views: 42

Answers (3)

anubhava
anubhava

Reputation: 784998

You may use this regex using multiple lookaround assertions:

(?<=\s)\d+\b(?!-\d+)(?=.*Minimum)

RegEx Demo

Explanation:

  • (?<=\s): Negative lookbehind to assert that we have a whitespace at previous position
  • \d+\b: Match 1+ digits followed by word boundary assertion
  • (?!-\d+): Negative lookahead to assert that we don't have -<digits> ahead
  • (?=.*Minimum): Lookahead to assert that we have Minimum text ahead

Upvotes: 0

Yu Jiaao
Yu Jiaao

Reputation: 4714

$str = "Red  QQ-4555 White  TT-789 123 Yellow Minimum order applies. This is a test ";
$explodeByMinimumArray = preg_split("/minimum/i", str_replace(array( '(', ')' ), ' ', $str));   
preg_match_all('/\s+\d+(?!-\d)/', $explodeByMinimumArray[0], $numberFromStringBeforeMinimumArray);  
print_r($numberFromStringBeforeMinimumArray);

will give

Array
(
    [0] => Array
        (
            [0] =>  123
        )

)

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626738

You need to use a negative lookbehind to ensure you do not match digits that are preceded with a letter/digit and a -:

(?<![\p{L}\d]-|\d)\d+(?!-\d)

See the regex demo.

Details

  • (?<![\p{L}\d]-|\d) - a negative lookbehind that fails the match if there is a letter or digit followed with - or a single digit immediately to the left of the current location
  • \d+ - 1+ digits
  • (?!-\d) - a negative lookahead that fails the match if there is a - and then a digit immediately to the right of the current location

Upvotes: 1

Related Questions