matcher.group(1)没有返回结果

时间:2013-07-21 19:03:00

标签: java android design-patterns matcher

    public class GetProp extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        String file_proc = readFile();
        TextView tv = (TextView)findViewById(R.id.tv);
        tv.setText("Read File contents from SDCARD : \n" + file_proc);
    }
    public String readFile(){
        BufferedReader rdr;
        String proc = "";
        String line;
        int lineNumber = 0;
        try {
            rdr = new BufferedReader(new FileReader("/proc/cpuinfo"));     
            while ((line = rdr.readLine()) != null) {
                lineNumber++;
            Matcher matcher = Pattern.compile("Processor: (.*)").matcher(line);
            if (matcher.find()) {
                proc = matcher.group(1);
            }
            }           
        } catch (Exception e) {
            e.printStackTrace();
        }
        return proc;        
    }
}

我想从/ proc / cpuinfo txt文件中打印一行,如Processor:“RESULT”,其中RESULT是matcher.group(1)。但是我的结果没有文字,我的问题在哪里?

1 个答案:

答案 0 :(得分:2)

这就是我/proc/cpuinfo的样子:

processor   : 0
vendor_id   : GenuineIntel
cpu family  : 6
model       : 42
/* etc */

你的正则表达式存在两个问题:

  1. 正则表达式区分大小写。将其更改为processor,或使用Pattern.compile(..., Pattern.CASE_INSENSITIVE)
  2. processor和冒号之间有空格。您应该将正则表达式更改为processor\\s*: (.*)