我有一个多行字符串,其中包含:
this is line 1
------------------------------
this is line 2
+++++++++++++++++++++++++
this is line 3
---------------
this is line 4
我想通过分割仅包含 (-,+) 的行来将此字符串分成 block ,我尝试了正则表达式 (^++$)|(^-+$) 在正则表达式验证器上运行良好,但它是不在 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)
请参阅Scala demo
注意,我还通过使用单个分组结构(如 ^(\++|-+)$
)来缩短模式。它匹配行的开头,然后匹配 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)
关于regex - Scala 按包含所有连字符的行拆分多行字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43454775/