Regular expression to match the last integer in a string with php and javascript

hoogsoadaky

New Member
I need to match the last integer in a string and capture possible elements before and after the last integer, assuming that the string can be composed of a single integer or a combination of text and/or integers.Let say that $str can be:
  • '123' -> '' - 123 - ''
  • 'abc 123' -> 'abc ' - 123
  • 'abc 123 def' -> 'abc ' - 123 - ' def'
  • 'abc 123 def 456' -> 'abc 123 def ' - 456
  • etc.
I expected that the following piece of code in php would do the job:\[code\]$str = 'abc 123 def 456 ghi';preg_match('/(.*)(\d+)(\D*)$/', $str, $matches);echo 'Matches = ' . implode(' : ', $matches);\[/code\]But the (\d+) is picking up only one digit:\[code\] Matches = abc 123 def 456 ghi : abc 123 def 45 : 6 : ghi\[/code\]While I was expecting:\[code\] Matches = abc 123 def 456 ghi : abc 123 def : 456 : ghi\[/code\]I get the same behavior in Javascript.The (.*) is that greedy to impinge on (\d+)?Thanks in advance!
 
Back
Top