我在android中使用正则表达式来读取用户输入,如下所示: 1:10和3:20 D20 3:10
(只是要知道,我把这个输入发送到arduino)
我需要验证用户是否断线,如果是,我将线路发送到arduino。如果该行以'(如第二个)开头,则会设置延迟,时间将是该行中的下一个整数;
这是我的代码,但问题是当我尝试验证匹配器是否找到我在编译中设置的内容
final String expression = aux.getCodigo().toString();
//System.out.println("mandeii " + MenuActivity.mIn.read());
Pattern pattern = Pattern.compile("'(\n)'");
Matcher matcher = pattern.matcher(expression);
System.out.println("achei ");
if (matcher.find()){
System.out.println("found the first endLine"+ matcher);
if (matcher.group(0).charAt(0) == 'd') {
System.out.println("achei o d "+matcher.group(0).charAt(0));
int v1 = matcher.group(0).charAt(1);
if (matcher.group(0).charAt(2) != '\n') {
int v2 = matcher.group(0).charAt(2);
int valor = Integer.parseInt(String.valueOf(v1) + String.valueOf(v2));
System.out.println("valor "+valor);
new CountDownTimer(valor * 1000, 1000) {
public void onFinish() {
System.out.println("delayed");
}
public void onTick(long millisUntilFinished) {
// millisUntilFinished The amount of time until finished.
}
}.start();
} else {
new CountDownTimer(v1 * 1000, 1000) {
public void onFinish() {
System.out.println("delayed");
}
public void onTick(long millisUntilFinished) {
// millisUntilFinished The amount of time until finished.
}
}.start();
}
}
else MenuActivity.mOut.write(matcher.group(0).getBytes());
如果有人知道,这会对我有很大帮助, tks
答案 0 :(得分:0)
所以,你只需要将行分成块(片段),使用\ n作为块分隔符。对?那么为什么要让它变得如此复杂,因为有一个很好的 split 方法:
// This must run in a NON-UI thread!
//=====================================
try {
for (String chunk: expression.split("\n")) {
if (chunk.charAt(0) == 'd') {
int valor;
if (chunk.length() > 1 &&
(valor = Integer.parseInt(chunk.substring(1)))> 0) {
System.out.println("Delay " + valor + " millisec");
Thread.sleep(valor);
}
} else
MenuActivity.mOut.write(chunk.getBytes());
} // End of for loop
} catch(InterruptedException ex) {
System.out.println("Cancelled");
}
}