David Godoy
David Godoy

Reputation: 31

Remove Java substring with regex

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

Answers (5)

laughing buddha
laughing buddha

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

Pedro Lobito
Pedro Lobito

Reputation: 98881

aString.replaceAll("[^/]+#", "#");

Demo and Explanation

Upvotes: 0

Viliam Aboši
Viliam Aboši

Reputation: 447

This should work aString.replaceAll("/[^/]*#", "#")

The above regex matches slash / and any number of nonslash [^/] characters followed by hash #.

Upvotes: 0

anubhava
anubhava

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 #

RegEx Demo

Upvotes: 1

Jorge Campos
Jorge Campos

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

Related Questions