Remove text from String via Regexp

in Java I want to remove some text from the following String via Regexp:

someText

begin
  .someMethod()
  .doSomething(TOKEN_123)
  .someMethod()
end

begin
  .someMethod()
  .doSomething(TOKEN_456)
  .someMethod()
end

begin
  .someMethod()
  .doSomething(TOKEN_789)
  .someMethod()
end

more Text

I want to remove the 2nd begin/end-Block which includes the String TOKEN_456.

Currently my regexp looks like the following

begin.*TOKEN_456(.*?)end

but this one removes the first AND second block.

Can anyone help please?

Greetz

Answers


You can use

str = str.replaceFirst("(?s)begin(?:(?!begin).)*TOKEN_456.*?end\\s*", ""));

See the IDEONE demo and a regex demo.

The regex matches:

  • (?s) - a singleline modifier
  • begin - matches the leading boundary, a character sequence begin
  • (?:(?!begin).)* - a tempered greedy token that matches any text that is not starting the word begin
  • TOKEN_456 - a literal character sequence to match
  • .*?end - any number of any characters as few as possible, up to the closest end
  • \\s* - 0 or more whitespace (for trimming purposes).

Need Your Help

recursion versus iteration

algorithm recursion iteration

Is it correct to say that everywhere recursion is used a for loop could be used? And if recursion is usually slower what is the technical reason for ever using it over for loop iteration?

How do I change an Android Snackbar's initial alignment from bottom to top?

android material-design android-design-library snackbar android-snackbar

The recent android library came out just a few days ago, but I would like to have the SnackBar appear on top of the screen, preferably within a RelativeLayout as it's parent view.