Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace a String between two Strings

Tags:

java

regex

Let's say we have something like:

&firstString=someText&endString=OtherText

And I would like to replace "someText" with something else. What is the best way to do this considering the fact that I do not know what someText might be (any string) and all I know is that it will be surrounded with &firstString= and &endString=

Edit: sorry looks like this is not clear enough. I do not know what "someText" might be, the only information I have is that it will be between &firstString= and &endString=

I was thinking about using split multiple times but it sounded ugly ..

like image 579
user220755 Avatar asked May 01 '12 20:05

user220755


People also ask

How do I replace a string from one string to another?

To replace one string with another string using Java Regular Expressions, we need to use the replaceAll() method. The replaceAll() method returns a String replacing all the character sequence matching the regular expression and String after replacement.

How do I replace a string between two strings in Java?

One of the simplest and straightforward methods of replacing a substring is using the replace, replaceAll or replaceFirst of a String class.

How do I replace string between two characters in Python?

sub() function. In Python, the . replace() method and the re. sub() function are often used to clean up text by removing strings or substrings or replacing them.

What is replace () method?

The replace() method returns a new string with one, some, or all matches of a pattern replaced by a replacement . The pattern can be a string or a RegExp , and the replacement can be a string or a function called for each match. If pattern is a string, only the first occurrence will be replaced.


1 Answers

You can use String#replaceAll that has support for regex like this:

String newstr = str.replaceAll("(&firstString=)[^&]*(&endString=)", "$1foo$2");
like image 66
anubhava Avatar answered Oct 09 '22 15:10

anubhava