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.
A regular expression to match everything before a specific character makes use of a wildcard character and a capture group to store the matched value. Another method involves using a negated character class combined with an anchor.
$ means "Match the end of the string" (the position after the last character in the string).
The dot matches all except newlines (\r\n). So use \s\S, which will match ALL characters.
The fundamental building blocks of a regex are patterns that match a single character. Most characters, including all letters ( a-z and A-Z ) and digits ( 0-9 ), match itself. For example, the regex x matches substring "x" ; z matches "z" ; and 9 matches "9" .
Regex: match last occurrence. The key to the solution is a so called “ negative lookahead “. A lookahead doesn’t consume characters in the string, but only asserts whether a match is possible or not. Of course the example is not taken from a real life scenario as it doesn’t matter which “foo” is matched as they’re all the same anyway.
This will match any single character at the beginning of a string, except a, b, or *c. If you add a * after it – /^ [^abc]*/ – the regular expression will continue to add each subsequent character to the result, until it meets either an a, or b, or c.
The ? symbol after .* and some other RegEx sequences means “match as little as possible.” If you look at the previous picture, you will see that text “lua” is seen twice in every match, and everything up to the second “lua” was matched. If you wanted to match everything up to the first occurrence of "lua" instead, you would use the following RegEx:
If you want to match everything after the first occurrence of a character, use Method 1. For everything after the last occurrence of a character, use Method 2. Method 3 will serve the same purpose, but only if look-behinds are supported.
You can match this:
.*\/
and replace with your text.
DEMO
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With