ant regex for android package names

2019-05-08 03:34发布

问题:

in my android project all of my .java view files import the R file based on the name of the current package. When I change the name of my package name in the Android Manifest (dynamically, not refactoring via Eclipse or any other IDE), I need to the references of all my java files to point to the new R file that gets generated

I am making a build script via Ant, but I am not sure what the regular expression convention would look like

The strings that need to be replaced look like this:

import com.mysite.myapp.R;

ie.

import com.sushiroll.california.R

This is what I have in my ant build script

<replaceregexp file="src/*"
           match="import*.R"
           replace="import ${current.package}.R"
           byline="true">
        <fileset dir="src/.">
            <include name="*.java"/>
        </fileset>
</replaceregexp>

where I want to match all strings that say import and end in .R

and replace it with import $current.package}.R

how would I word that for ant regex? the match and replace that I wrote were just guesses

回答1:

You need to group old package name chars before .R

if you know package name

    match="import com\.mysite\.myapp\.R;"

if you do now know package name, but be prepared to be failed for wrong imports if you import R from different packages

    match="import (.*).R;"

replace to

replace="import ${current.package}.R;"

and the

    <fileset dir="src">
        <include name="**/*.java"/>
    </fileset>


回答2:

<replaceregexp
   match="import .+?\.R;"
   replace="import ${current.package}.R;"
   flags="g"
> 
...

where +? is needed so that it works if you have two imports in a line, and g needed so not only one import per file is replaced. Although currently you only have one per file since you replace all of them with the same string, this is the universally correct regexp...