0

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.

1
  • probably change .* to [^/]. Commented Apr 20, 2017 at 18:35

5 Answers 5

2

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 #

Sign up to request clarification or add additional context in comments.

2 Comments

You may slightly improve this with .replaceFirst("(.*/)[^#]*", "$1");
Hi @WiktorStribiżew That's an entirely new version for an answer. You can add it and I will upvote it gladly since uses almost the same Idea as mine one.
1

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

3 Comments

Hi Anubhava, will this [^/#] consider the inverse order?
Sorry, can you clarify what you mean by inverse order here?
I'm sorry I didn't saw the precedent / before the [^/#] pattern, though my question is irrelevant. Thanks for the attention :)
0

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

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

Comments

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

Demo and Explanation

2 Comments

This one has lot of backtracking (check in regex debugger on regex101)
Fair enough, but if I change it now, I'll end-up with a regex like yours which has only 38 steps! tks for pointing that.
0
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.