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
but this one removes the first AND second block.
Can anyone help please?
You can use
str = str.replaceFirst("(?s)begin(?:(?!begin).)*TOKEN_456.*?end\\s*", ""));
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).