11

I want to remove a string that is between two characters and also the characters itself , lets say for example:

i want to replace all the occurrence of the string between "#?" and ";" and remove it with the characters.

From this

"this #?anystring; is  #?anystring2jk; test"

To This

"this is test"

how could i do it in java ?

f1sh
  • 11,489
  • 3
  • 25
  • 51
Jimmy
  • 10,427
  • 18
  • 67
  • 122

3 Answers3

21

@computerish your answer executes with errors in Java. The modified version works.

myString.replaceAll("#\\?.*?;", "");

The reason being the ? should be escaped by 2 backslashes else the JVM compiler throws a runtime error illegal escape character. You escape ? characters using the backslash .However, the backslash character() is itself a special character, so you need to escape it as well with another backslash.

A_Var
  • 1,056
  • 1
  • 13
  • 23
  • 2
    I don't understand how the answer by computerish has 2 votes. Is it fixed or what???. – A_Var Sep 21 '10 at 04:02
  • Can you help me understand the second ?. I am trying to replace everything between a : and a \n and ":.*\n" is working for me. What does the second ? do? – Travis Needham Dec 13 '17 at 17:34
  • This should be the accepted answer, as the now accepted one does not work. – Akito Feb 22 '21 at 11:45
12

Use regex:

myString.replaceAll("#\?.*?;", "");
Computerish
  • 9,590
  • 7
  • 38
  • 49
5

string.replaceAll(start+".*"+end, "")

is the easy starting point. You might have to deal with greediness of the regex operators, however.

Carl
  • 7,538
  • 1
  • 40
  • 64