[英]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. 当一行与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 想要在正则表达式而不是\\ n中使用^和$进行检查
You may use 您可以使用
val key = "GO"
val res = s1.stripMargin('|').split(s"(?mi)^\\s*${key}\\s*$$[\r\n]*")
See the Scala demo 观看Scala演示
The regex split is applied after stripMargin('|')
is used to remove the indentation first. 在使用stripMargin('|')
首先删除缩进之后,将应用正则表达式拆分。
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 (?mi)
-整个图案是不区分大小写如i
是不区分大小写的改性剂和m
使得^
和$
的线的匹配的开始/结束而不是字符串 ^
- the beginning of a line ^
-行首 \\\\s*
- 0 or more whitespaces \\\\s*
-0或多个空格 ${key}
- the value of key
(note you might need Pattern.quote
to escape any special chars in that variable) ${key}
-值key
(注意,您可能需要Pattern.quote
转义任何特殊字符在该变量) \\\\s*
- trailing line whitespace \\\\s*
-尾随空格 $$
- 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. [\\r\\n]*
-零个或多个CR或/和LF换行符。 s1.split( "(?m)^(\\s*(?i)%s)\\s*$[\r\n]*".format("GO"))
高于最终答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.