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
答案 0 :(得分: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