1

I am expecting to remove lines b/w "& Hello Buddy" and "&endmarker&" inclusive. I used replaceAll like shown below and doesn't work any help pls...

val s1 =
  """
    |& Hello Buddy
    |------------------------------
    |Hello;
    |GO
    |My
    |use &endmarker&
    |   GO
    |World
    |go
    |, I am Naga
    |+++++++++++++++++++++++++
    |GOTO School
    |GO Heaven
  """


val rg =s1.replaceAll("(?m)&(.*)&endmarker&" ," ")

1 Answer 1

3

I suggest

val rg =s1.stripMargin('|').replaceAll("(?s)& Hello Buddy(.*?)&endmarker&" ," ").trim()

Output:

GO
World
go
, I am Naga
+++++++++++++++++++++++++
GOTO School
GO Heaven

See the Scala demo

The .stripMargin('|') will get rid of the indentation.

Pattern details

  • (?s) - a DOTALL modifier, . matches any chars including line break chars
  • & Hello Buddy - a literal string
  • .*? - any 0+ chars as few as possible up to the first occurrence of...
  • &endmarker& - a literal string.

If you have a big file to process, the pattern should be re-written for better performance as

"(?s)& Hello Buddy[^&]*(?:&(?!endmarker&)[^&]*)*&endmarker&"

where .*? lazy dot is replaced with an unroll-the-loop pattern [^&]*(?:&(?!endmarker&)[^&]*)* that matches

  • [^&]* - 0+ chars other than &
  • (?:&(?!endmarker&)[^&]*)* - zero or more occurrences of:
    • &(?!endmarker&) - a & not followed with endmarker&
    • [^&]* - 0+ chars other than &
Sign up to request clarification or add additional context in comments.

Comments

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.