1

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

3
  • I guess you have the singleline flag. Why not split by multiple newlines and remove the element of the resulting array, and then joining the rest? BTW, you are looking for begin(?:(?!begin).)*TOKEN_456(.*?)end. Commented Dec 4, 2015 at 8:15
  • @tripleee: Not this one for sure. Commented Dec 4, 2015 at 8:18
  • As I mentioned, the dupe was absolutely incorrect, it is not solved with negated character class or lazy dot matching, thus relieved the close vote. Commented Dec 4, 2015 at 12:15

1 Answer 1

2

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).
Sign up to request clarification or add additional context in comments.

3 Comments

You can improve performance of the regex if you add more "anchoring" details, like word boundaries, start of line anchor, newlines: "(?sm)^begin\\b(?:(?!\\bbegin\\b).)*TOKEN_456(.*?)\nend(?:$|\n)".
Just noticed a capturing group on (.*?) - I guess you can remove the parentheses if you are not interested in the captured text.
ah good to know. Thought I always have to use brackets in this context

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.