我是Android上的菜鸟,我正在尝试提取Android日志的PID,但是当我尝试使用正则表达式时,不要将值提取到我的变量中。日志消息的格式如下:
E/AndroidRuntime(14700): Process: com.example.log_v_02, PID: 14700
但有时格式是这样的:
E/AndroidRuntime( 4700): Process: com.example.log_v_02, PID: 14700
第一个"("后面有一个空格
我正在使用模式和匹配器类来制作它,这是我的代码:
Pattern saca_pid = Pattern.compile(".*( [0-9]{1,4}).*||.*([0-9]{5,}).*");
StringBuilder log=new StringBuilder();
String line = "";
while (true) {
try {
if (!((line = bufferedReader.readLine()) != null)) break;
} catch (IOException e) {
e.printStackTrace();
}
Boolean matches = Pattern.matches(patron_malicioso,line);
Matcher encuentra_pid = saca_pid.matcher(line);
if(encuentra_pid.find())
{
String pid = encuentra_pid.group(1);
}
}
正
则表达式交替是单个管道,即 |
,而不是双管||
,这是逻辑上的OR。 对代码的确切修复是:
Pattern saca_pid = Pattern.compile(".*( [0-9]{1,4}).*|.*([0-9]{5,}).*");
解决此问题可能会使您的代码正常工作,但我建议使用以下模式:
(s*(d+)):
您更新的代码:
Pattern saca_pid = Pattern.compile("\(\s*(\d+)\):");
StringBuilder log = new StringBuilder();
String line = "";
while (true) {
try {
if (!((line = bufferedReader.readLine()) != null)) break;
} catch (IOException e) {
e.printStackTrace();
}
Matcher encuentra_pid = saca_pid.matcher(line);
if (encuentra_pid.find()) {
String pid = encuentra_pid.group(1);
}
}
更新后的模式完全避免了交替的需要,使数字前面的前导空格可选。