简体   繁体   中英

Split a multi-line string when a line matches a substring in Scala

Split a multi-line string when a line matches a substring in Scala. Below is the same snippet code. But I would like to use proper regex.

val s1 =
  """
    |Hello;
    |------------------------------
    |GO
    |World
    |go
    |True
    |            GO
    |,I am Naga
    |+++++++++++++++++++++++++
    |GOTO School
    |GO Heaven
  """
s1.split("\n(?i)GO\n")

Output:

Hello;
------------------------------
World
True
,I am Naga
+++++++++++++++++++++++++
GOTO School 
GO Heaven

want to check using ^ and $ in regex instead of \\n

You may use

val key = "GO"
val res = s1.stripMargin('|').split(s"(?mi)^\\s*${key}\\s*$$[\r\n]*")

See the Scala demo

The regex split is applied after stripMargin('|') is used to remove the indentation first.

Pattern matches :

  • (?mi) - the whole pattern is case insensitive as i is the case insensitive modifier and m makes ^ and $ match start / end of a line rather than a string
  • ^ - the beginning of a line
  • \\\\s* - 0 or more whitespaces
  • ${key} - the value of key (note you might need Pattern.quote to escape any special chars in that variable)
  • \\\\s* - trailing line whitespace
  • $$ - it is in fact a single literal $ - end of a line (it is doubled as the string literal is an interpolated one where $ is used to introduce code)
  • [\\r\\n]* - zero or more CR or/and LF line break chars.
s1.split( "(?m)^(\\s*(?i)%s)\\s*$[\r\n]*".format("GO"))

高于最终答案。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM