2017-01-12 5 views
0

읽기 직렬 포트 체중 추기경 규모,C#을 내 컴퓨터에 표시의 데이터를 표시 할 수있었습니다 (210)

출력보기와 같은 -이

"[SPACE] [SPACE] 978 0kg "

[SPACE]를 (빈) 공간 텍스트 나 숫자 만 표시 할

입니다

,

다음 스크립트를 사용합니다. 마지막 숫자 0은 입력하지 않은

private delegate void Closure(); 
    private void SerialPortOnDataReceived(object sender, SerialDataReceivedEventArgs serialDataReceivedEventArgs) 
    { 
     if (InvokeRequired)  //<-- Makes sure the function is invoked to work properly in the UI-Thread 
      BeginInvoke(new Closure(() => { SerialPortOnDataReceived(sender, serialDataReceivedEventArgs); }));  //<-- Function invokes itself 
     else 
     { 
      while (_serialPort.BytesToRead > 0) //<-- repeats until the In-Buffer is empty 
      { 
       String tampung = _serialPort.ReadExisting(); 
       Regex regex = new Regex(@"[^\d|\.]"); 

       tampung = regex.Replace(tampung, ""); 


       textBox1.Text += string.Format("{0:X2} ", tampung); 
      } 
     } 
    } 

하지만 불완전한 수치를 표시

출력 :

978

내가 표시를 http://www.cardinalscale.com/cs_product/210-storm/

이되어 사용하고 있습니다 뭔가 잘못 됐어?

답변

0

Regex를 사용하여 문자열에서 숫자를 추출한 다음 Trim 공백을 제거 할 수 있습니다.

string input = " 940 0Kg"; 
string result = Regex.Replace(input, @"[^\d]", "").Trim(); 

그리고 당신은 물론, 숫자로 필요하면

int weight = int.Parse(result); 
0

는 교체

String tampung = _serialPort.ReadExisting(); 
Regex regex = new Regex(@"[^\d|\.]"); 

string tampung = _serialPort.ReadExisting(); 
string pattern = @"(\d+\.\,\d+)"; 
MatchCollection matches = Regex.Matches(tampung, pattern);