0

I have a string that is uncertain,I have the following strings:
ST,NT,+ 16KG ~YT,NT,+ 16KG
ST,NT) 16KG +YT,N,+ 16KG
ST,NT,+ 16KG and etc.

My question is there any regex only take 16KG or 16, because the string output from digital scale.
I'm working on an application with serial port, so I can not parsing the data there, while in the output on digital scale tool is only 16KG.

Loren Ramly
  • 1,091
  • 4
  • 13
  • 21
  • * See also [Open source RegexBuddy alternatives](http://stackoverflow.com/questions/89718/is-there) and [Online regex testing](http://stackoverflow.com/questions/32282/regex-testing) for some helpful tools, or [RegExp.info](http://regular-expressions.info/) for a nicer tutorial. – mario Dec 25 '12 at 17:41
  • possible duplicate of [Read data from port get result fickle data](http://stackoverflow.com/questions/14015683/read-data-from-port-get-result-fickle-data) – mario Dec 25 '12 at 17:42
  • Mario there i get no answer, you can see who is quest there. – Loren Ramly Dec 25 '12 at 17:47
  • Hi all, this issue is over, thank you've helped me. – Loren Ramly Dec 25 '12 at 18:26

1 Answers1

0

So you want to get the digits before KG?

try this:

<?php
    $input = 'ST,NT,+ 16KG ~YT,NT,+ 16KG';
    preg_match('/(\d+)KG/',$input,$matches);
    echo $matches[1];
?>

output:

16
howanghk
  • 3,070
  • 2
  • 21
  • 34
  • Hi owen, thanks for reply, i get error, when i print_r($matches) i get array with empty data. – Loren Ramly Dec 25 '12 at 17:46
  • can you show your full code? My code did work for your sample inputs: http://ideone.com/nTYDSa – howanghk Dec 25 '12 at 17:49
  • I want to ask one question again, what if on output digital scale will be a minus with regex above, for example -2KG, and then example i get string is 'ST,NT,+ -2KG ~YT,NT,+ -2KG', i tried, and it only show 2KG, without minus it. Thanks. – Loren Ramly Dec 25 '12 at 18:00
  • If you want to allow minus, change `(\d+)` to `(-?\d+)` – Barmar Dec 25 '12 at 18:07
  • Hi Mr Barmar this work for me, many2 thanks for Mr Barmar and Mr Owen, i give you thumb up. Thanks. – Loren Ramly Dec 25 '12 at 18:13