2014-03-27 127 views
0

我想寫一個python腳本,將一些java代碼添加到一個java源文件。爲什麼我的模式不匹配?

#!/usr/bin/env python 

import sys, getopt 
import re 

def read_write_file(infile): 
     inf = open(infile, 'r') 
     pat = re.compile('setContentView\(R\.layout\.main\)\;') 
     for line in inf: 
       l=line.rstrip() 
       if (pat.match(l)): 
         print l 
         print """ 
      // start more ad stuff 
      // Look up the AdView as a resource and load a request. 
      AdView adView = (AdView)this.findViewById(R.id.adView); 
      AdRequest adRequest = new AdRequest.Builder().build(); 
      adView.loadAd(adRequest); 
      // end more ad stuff 

""" 
         sys.exit(0) 
       else: 
         print l 
     inf.close 


def main(argv): 
     inputfile = '' 
     try: 
       opts, args = getopt.getopt(argv,"hi:",["ifile="]) 
     except getopt.GetoptError: 
       print 'make_main_xml.py -i <inputfile>' 
       sys.exit(2) 
     for opt, arg in opts: 
       if opt == '-h': 
         print """ 
usage : make_main_activity.py -i <inputfile> 

where <inputfile> is the main activity java file 
like TwelveYearsaSlave_AdmobFree_AudiobookActivity.java 
""" 
         sys.exit() 
       elif opt in ("-i", "--ifile"): 
         inputfile = arg 
     read_write_file(inputfile) 

if __name__ == "__main__": 
     main(sys.argv[1:]) 

...這裏是典型的輸入文件,該腳本上運行...

public static Context getAppContext() { 
      return context; 
    } 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 
      context = getApplicationContext(); 
      setContentView(R.layout.main); 


} 

...實際的Java源文件是巨大的,但我只是想插入文本。 ..

  // start more ad stuff 
      // Look up the AdView as a resource and load a request. 
      AdView adView = (AdView)this.findViewById(R.id.adView); 
      AdRequest adRequest = new AdRequest.Builder().build(); 
      adView.loadAd(adRequest); 
      // end more ad stuff 

...右後...

  setContentView(R.layout.main); 

...但是當我運行腳本時,我想要插入的文本不會被插入。 我認爲有什麼不對的這條線在我的Python腳本...

 pat = re.compile('setContentView\(R\.layout\.main\)\;') 

...我已經嘗試了許多不同的其他字符串進行編譯。我究竟做錯了什麼?

感謝

+0

'inf.close'應該是'inf.close()' –

回答

1

pat.match(l)必須與字符串完全匹配。這意味着在這種情況下l必須是"setContentView(R.layout.main);"

不過,既然你setContentView(...)前有空格,你應該使用pat.search(l)代替,或更改

pat = re.compile('setContentView\(R\.layout\.main\);') 

pat = re.compile('^\s*setContentView\(R\.layout\.main\);\s*$') 

匹配的空間。

此外,在這種情況下,你不需要正則表達式。您可以通過使用in運算符來檢查該行是否包含字符串。

if "setContentView(R.layout.main);" in l: 
+0

真棒謝謝! –

相關問題