为什么我的模式不匹配?

时间:2014-03-27 04:07:31

标签: python regex

我正在尝试编写一个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\)\;')

...我已经尝试了很多其他的字符串来编译。我做错了什么?

谢谢

1 个答案:

答案 0 :(得分: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: