John Powel
John Powel

Reputation: 1424

How to replace using regular expression in nested string?

I have this: start_xxx_end_Leftstart_xxx_end_Right

How can I use the regular expression to remove characters between start and end (inclusive) so that I can get the following string:

_Left_Right

I tried this regex in java but it removes EVERYTHING between start and end:

start(.*)end

Upvotes: 0

Views: 202

Answers (1)

Rohit Jain
Rohit Jain

Reputation: 213311

Just use replaceAll method to replace the substring from start to end: -

String str = "start_xxx_end_Leftstart_xxx_end_Right";
str = str.replaceAll("start.*?end", "");
System.out.println(str);

OUTPUT : -

"_Left_Right"

Upvotes: 3

Related Questions