使用 GNU 读取连续数据时在 try 内调用匹配器函数

问题描述 投票:0回答:1
case SerialPortEvent.DATA_AVAILABLE:

      byte[] readBuffer = new byte[64];
     try {
            // read data
            int numBytes = inputStream.read(readBuffer);
            inputStream.close();
            //-------------------------------
           //send the received data to the GUI
            String result = new String(readBuffer,0,numBytes);
            //-----------------------------
            gui.setjtaReceived(result);

            matcher(result,writer,df);
            //gui.setjtaReceived(result);
     }
     catch (IOException e) {exceptionReport(e);}

在上面的 SerialPortEvent.Dat_Available 开关案例中,我正在实时接收连续数据。匹配器函数调用下面定义的函数

    private void matcher(String str,FileWriter writer,DateFormat df) {
    Matcher m1 = p1.matcher(str);
    Matcher m2 = p2.matcher(str);
    System.out.println(m1.group());
    Calendar cal = Calendar.getInstance();
    String match_heartBeat = null;
    String match1 = m1.group();
    int length1 = match1.length();
    if(m2.find()){
        String match2 = m2.group();
        int length2 = match2.length();
        match_heartBeat = match2.substring(2, length2-1);
        //System.out.println(match1.subSequence(2, 4) + ";" + match_heartBeat);
    }
    String realTime = df.format(cal.getTime());
    writer.append(realTime);
    writer.append(',');
    writer.append(match1.subSequence(2, length1-1));
    writer.append(',');
    writer.append(match_heartBeat);
    writer.append('\n');
    writer.flush();


 }

当我尝试写入外部 csv 文件,甚至执行 System.out.println(m1.group) 或 System.out.println(match_heartBeat) 时,我无法将其写入文件或打印到屏幕。但是 System.out.println(m1) 打印在屏幕上。知道如何克服这个问题吗?我正在尝试解码实时接收的数据。 图案如下:

    Pattern p1 = Pattern.compile("\\b(a)\\w*( )\\b");
    Pattern p2 = Pattern.compile("\\b(')\\w*( )\\b");

它会查找字母 'a' 直到空格,然后查找 ' 到空格。一旦程序开始运行,就会生成文件“writer”。但可以附加解码后的数据。

样本数据:

79 0009a017 009a047 9%0009a047 90009a046 9%0009a0469 0009a045 9%0009a0459'00 90009a045 9%0009a044 90009a044 9%0009a044 9 

样本输出 CSV 文件

System time , 17 , 00
java regex serial-port
1个回答
1
投票

让我们根据评论来澄清规范。这是输入字符串:

79 0009a017 009a047

这是输出字符串:

017,00

“017”是十进制(不是八进制)数字。稍后格式化为“17”可能会方便。

正如评论中提到的,这个正则表达式是不正确的:

Pattern p1 = Pattern.compile("\\b(a)\\w*( )\\b");

应该是:

Pattern p1 = Pattern.compile("a(\\d+) (\\d{2})");

快速演示:

echo "79 0009a017 009a047" | perl -lne 'print $1,",",$2 if /a(\d+) (\d{2})/'
017,00
© www.soinside.com 2019 - 2024. All rights reserved.