Tuesday, May 3, 2011

How can I strip a substring from a string with a regular expression?

Hi, I have a classpath, something like:

myproject/classes;myproject/lib/somecrab.zip;myproject/lib/somelib1.jar;myproject/lib/somelib2.jar;myproject/lib/somelib3.jar;

Now I would like to clean up this classpath and throw away somethings which I don't want anymore. Hence in this case the classpath should look something like

myproject/classes;myproject/lib/somelib1.jar;myproject/lib/somelib3.jar;

How can I do that with a regular expression? I want to do it with an ant-Script, e.g.

<pathconvert property="new.classpath" pathsep=";">
    <path refid="old.classpath" />
    <chainedmapper>
        <regexpmapper from="(.*).jar" to="\1.jar" />
    </chainedmapper>
</pathconvert>

How do I need to adapt the regexp? Thanks a lot!

From stackoverflow
  • I think you would need to phrase it as (validstuffbefore)skipstuff(validstuffafter) and then use a replace string of \1\2

    So (possibly):

    ^([\w/]+;)((?:[\w/]+\.jar;)*)[\w/]+\.zip;?((?:[\w/]+\.jar;)*)$
    

    And replace with:

    \1\2\3
    

    You may have issues with multiple matches, but the global flag should resolve that.

    Good luck!

  • If all you want to do is get rid of a contiguous string in the middle, it should just be:

    <regexpmapper from="(.*)myproject/lib/somecrab.zip;(.*)" to="\1\2" />
    
    Richard Szalay : +1 For exact strings, this is much easier to maintain than mine.
    blackicecube : I tried this, but unfortunately it doesn't work? My classpath string comes back empty?!
  • Why does

    <regexpmapper from="(^.*)crab\.zip(.*$)" to="\1bla\2bla" />
    

    for path

    myproject/classes;myproject/lib/othercrab.zip;myproject/lib/somelib1.jar;myproject/lib/somelib2.jar;myproject/lib/somelib3.jar;
    

    map to

    myproject/lib/otherblabla
    

    The second argument is always empty? Also I am missing all the stuff before "myproject/lib/other"

  • Rather than using a regex to transform the existing classpath, why not clean up the classpath to begin with? How are you building the old.classpath property to begin with?

0 comments:

Post a Comment