1

https://www.tehplayground.com/KWmxySzbC9VoDvP9

Why is the first string matched?

$list = [
    '3928.3939392',     //  Should not be matched
    '4.239,99',
    '39',
    '3929',
    '2993.39',
    '393993.999'
];

foreach($list as $str){
    preg_match('/^(?<![\d.,])-?\d{1,3}(?:[,. ]?\d{3})*(?:[^.,%]|[.,]\d{1,2})-?(?![\d.,%]|(?: %))$/', $str, $matches);
    print_r($matches);
}

output

Array
(
    [0] => 3928.3939392
)
Array
(
    [0] => 4.239,99
)
Array
(
    [0] => 39
)
Array
(
    [0] => 3929
)
Array
(
    [0] => 2993.39
)
Array
(
)
6
  • Why should it not be matched? What is the rule? Commented Dec 13, 2017 at 20:30
  • 2
    (?:[,. ]?\d{3})* matches like everything Commented Dec 13, 2017 at 20:30
  • For a detailed explanation of your current regex: regex101.com/r/ZoLUFf/1 Commented Dec 13, 2017 at 20:32
  • 1
    The (?<![\d.,]) is redundant as it always returns true: there can be no text before the start of the string. Try just ^-?(?:\d{1,3}(?:[,. ]\d{3})*|\d+)(?:[.,]\d{1,2})?$. Commented Dec 13, 2017 at 20:32
  • 1
    @WiktorStribiżew create an answer.. beautiful pattern :p Commented Dec 13, 2017 at 20:44

1 Answer 1

2

You seem to want to match the numbers as standalone strings, and thus, you do not need the lookarounds, you only need to use anchors.

You may use

^-?(?:\d{1,3}(?:[,. ]\d{3})*|\d*)(?:[.,]\d{1,2})?$

See the regex demo

Details

  • ^ - start of string
  • -? - an optional -
  • (?: - start of a non-capturing alternation group:
    • \d{1,3}(?:[,. ]\d{3})* - 1 to 3 digits, followed with 0+ sequences of ,, . or space and then 3 digits
    • | - or
    • \d* - 0+ digits
  • ) - end of the group
  • (?:[.,]\d{1,2})? - an optional sequence of . or , followed with 1 or 2 digits
  • $ - end of string.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.