Red Cricket
Red Cricket

Reputation: 10460

Why doesn't my pattern match?

I am trying to write a python script that will add some java code to a java source file.

#!/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:])

... here is the typical input file this script will operate on ...

    public static Context getAppContext() {
            return context;
    }

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


}

... the actual java source file is huge but I just want to insert the text ...

            // 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

... right after ...

            setContentView(R.layout.main);

... but when I run my script the text I want to insert does not get inserted. I assume there is something wrong with this line in my python script ...

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

... I have tried many various other strings to compile. What am I doing wrong?

Thanks

Upvotes: 0

Views: 61

Answers (1)

ymonad
ymonad

Reputation: 12090

pat.match(l) have to to match exactly with the string. It means that l must be "setContentView(R.layout.main);" in this case.

However , since you have spaces before setContentView(...), you should use pat.search(l) instead, or change

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

to

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

for matching spaces.

Moreover, in this case you don't need regex. You can just check that line contains the string by using in operator.

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

Upvotes: 1

Related Questions