25

Using a regular expression (replaceregexp in Ant) how can I match (and then replace) everything from the start of a line, up to and including the last occurrence of a slash?

What I need is to start with any of these:

../../replace_this/keep_this

../replace_this/replace_this/Keep_this

/../../replace_this/replace_this/Keep_this

and turn them into this:

what_I_addedKeep_this

It seems like it should be simple but I'm not getting it. I've made regular expressions that will identify the last slash and match from there to the end of the line, but what I need is one that will match everything from the start of a line until the last slash, so I can replace it all.

This is for an Ant build file that's reading a bunch of .txt files and transforming any links it finds in them. I just want to use replaceregexp, not variables or properties. If possible.

Community
  • 1
  • 1
user3762977
  • 651
  • 2
  • 15
  • 27
  • Thanks for the info, yes the first answer solved it completely, I had tried clicking "vote up" but it said I needed 15 points before I could vote, but I didn't know about the checkmark option which is available even to a newb here like me, so thanks and I've checked that one now. All of the answers were interesting to learn about what the regexp did, but that first one had solved it for me. Should I "accept" all? Thanks again. – user3762977 Jun 29 '14 at 03:46
  • BTW my above "Thanks for the info" comment was in response to a comment, now vanished, from someone letting me know about the checkmark feature to "accept" an answer. – user3762977 Jun 30 '14 at 18:26

3 Answers3

40

You can match this:

.*\/

and replace with your text.

DEMO

sshashank124
  • 31,495
  • 9
  • 67
  • 76
  • I need the opposite of this - match end from the last instance of a character - this is a solution: https://stackoverflow.com/a/8374980/845584 – PeterX Aug 02 '18 at 00:04
11

What you want to do is match greedily, the longest possible match of the pattern, it is default usually, but match till the last instance of '/'.

That would be something like this:

 .*\/

Explanation:

. any character
* any and all characters after that (greedy)
\/ the slash escaped, this will stop at the **last** instance of '/'

You can see it in action here: http://regex101.com/r/pI4lR5

3

Option 1

  • Search: ^.*/
  • Replace: Empty string
  • Because the * quantifier is greedy, ^.*/ will match from the start of the line to the very last slash. So you can directly replace that with an empty string, and you are left with your desired text.

Option 2

  • Search: ^.*/(.*)
  • Replace: Group 1 (typically, the syntax would be $1 or \1, not sure about Ant)
  • Again, ^.*/ matches to the last slash. You then capture the end of the line to Group 1 with (.*), and replace the whole match with Group 1.
  • In my view, there's no reason to choose this option, but it's good to understand it.
zx81
  • 41,100
  • 9
  • 89
  • 105