Reputation: 31
I'm trying to remove characters between /
and #
characters, my string is the following one:
platform:/this/is/a/path/contentToRemove#OtherContent
The replacement which I executed was:
aString.replaceAll("/.*?#", "#")
but what I was given in return was:
platform:#OtherContent
when I wanted:
platform:/this/is/a/path/#OtherContent
How should I have done this correctly using Regex? Is there any other solution to accomplish which I want?
Thanks.
Upvotes: 0
Views: 189
Reputation: 361
aString.replaceAll("(.*/).*#(.*)", "$1#$2");
This will catch all the string till last / and put that string in group 1, then it will look for #, following string will be put in group 2
Upvotes: 0
Reputation: 447
This should work aString.replaceAll("/[^/]*#", "#")
The above regex matches slash /
and any number of nonslash [^/]
characters followed by hash #
.
Upvotes: 0
Reputation: 784988
Use negated character class:
aString = aString.replaceAll("/[^/#]*#", "/#");
//=> platform:/this/is/a/path/#OtherContent
[^/#]*
is a negated character class that will find 0 or more of any characters that are not /
and #
Upvotes: 1
Reputation: 23361
That's because you use a Greed pattern. It will eat from the first occurrence of /
to the end pattern. You must use:
aString.replaceAll("(.*/).*?#", "$1#");
This will get everything until the last /
and group ($1
) and replace it with the content of group 1 and the #
Upvotes: 2