php - regexp - match numbers with two decimals and thousand seperator -


http://www.tehplayground.com/#0qrtozth3

$inputs = array(     '2', // no match     '29.2', // no match     '2.48',     '8.06.16', // no match     '-2.41',     '-.54', // no match     '4.492', // no match     '4.194,32',     '39,299.39',     '329.382,39',     '-188.392,49',     '293.392,193', // no match     '-.492.183,33', // no match     '3.492.249,11',     '29.439.834,13',     '-392.492.492,43' );  $number_pattern = '-?(?:[0-9]|[0-9]{2}|[0-9]{3}[\.,]?)?(?:[0-9]|[0-9]{2}|[0-9]{3})[\.,][0-9]{2}(?!\d)';  foreach($inputs $input){     preg_match_all('/'.$number_pattern.'/m', $input, $matches);     print_r($matches); } 

it seems looking

$number_pattern = '-?(?<![\d.,])\d{1,3}(?:[,.]\d{3})*[.,]\d{2}(?![\d.])'; 

see php demo , regex demo.

the anchors not used, there lookarounds on both sides of pattern instead.

pattern details:

  • -? - optional hyphen
  • (?<![\d.,]) - there cannot digit, comma or dot befire current location -\d{1,3} - 1 3 digits
  • (?:[,.]\d{3})* - 0 or more sequences of comma or dot followed 3 digits
  • [.,] - comma or dot
  • \d{2} - 2 digits are
  • (?![\d.]) - not followed digit or dot.

note in php, not need specify /m multiline mode , use $ end of string anchor,

preg_match_all('/'.$number_pattern.'/', $input, $matches); 

is enough match numbers need in larger texts.

if need match them standalone strings, use simpler

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

see regex demo.


Comments

Popular posts from this blog

Spring Boot + JPA + Hibernate: Unable to locate persister -

go - Golang: panic: runtime error: invalid memory address or nil pointer dereference using bufio.Scanner -

c - double free or corruption (fasttop) -