我在 android 中使用正则表达式来读取用户输入,它是这样的:1:10&3:20 d20 3:10
(只是想知道,我将此输入发送到 arduino)
我需要验证用户是否断线,如果是,我将线路发送到 arduino。如果该行以 'd' 开头(如第二个),它将设置一个延迟,时间将是该行中的下一个整数;
这是我的代码,但问题是当我尝试验证匹配器是否找到我在编译中设置的内容时
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
因此,您只需要使用 \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");
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句