Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace/remove String between two character [duplicate]

Tags:

java

string

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 ?

like image 745
Jimmy Avatar asked Sep 21 '10 01:09

Jimmy


3 Answers

Use regex:

myString.replaceAll("#\?.*?;", "");
like image 200
Computerish Avatar answered Nov 13 '22 06:11

Computerish


@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.

like image 21
A_Var Avatar answered Nov 13 '22 06:11

A_Var


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

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

like image 5
Carl Avatar answered Nov 13 '22 08:11

Carl