2014-03-27 130 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

真棒谢谢! –

相关问题