Regex Scala按包含所有连字符的行拆分多行字符串
我有一个多行字符串,其中包含:Regex Scala按包含所有连字符的行拆分多行字符串,regex,scala,split,Regex,Scala,Split,我有一个多行字符串,其中包含: this is line 1 ------------------------------ this is line 2 +++++++++++++++++++++++++ this is line 3 --------------- this is line 4 我想通过在只包含(-,+)的行上拆分来将这个字符串分成块,我尝试了正则表达式(^++$)|(^-++$),它在正则表达式验证器上运行良好,但在Scala中不起作用。您需要使用多行修饰符使
this is line 1
------------------------------
this is line 2
+++++++++++++++++++++++++
this is line 3
---------------
this is line 4
我想通过在只包含(-,+)的行上拆分来将这个字符串分成块,我尝试了正则表达式(^++$)|(^-++$),它在正则表达式验证器上运行良好,但在Scala中不起作用。您需要使用多行修饰符使
^
匹配行的开头和$
匹配行的结尾。此外,用\s*
(零个或多个空格)包围模式将修剪结果列表中的项目:
val rx = """(?m)\s*^(\++|-+)$\s*"""
val res = text.split(rx)
print(res.toList)
// => List(this is line 1, this is line 2, this is line 3, this is line 4)
见
注意,我还通过使用一个分组结构(如^(\++124;-+)$
)来缩短模式。它匹配行首,然后是1+加号或连字符,然后是行尾(因此,无需重复^
和$
)
另一种解决方案是使用换行符拆分字符串,然后过滤掉空行或仅包含加号或连字符的行:
print(text.split("\\r?\\n").filter(line=>line.matches("""(\++|-+)?""") == false).toList)
// => List(this is line 1, this is line 2, this is line 3 , this is line 4)
请参阅使用“(?m)(^\++$)|(^-++$)”
。