scala.util.matching.Regex
似乎只有一个split()
方法,其行为是提取匹配并仅返回输入字符串的不匹配段:
val str = "Here is some stuff PAT and second token PAT and third token PAT and fourth"
val r = "PAT".r
r.split(str)
res14: Array[String] = Array("Here is some stuff ", " and second token ", "
and third token ", " and fourth")
那么还有另一种常用于在返回列表中保留令牌的方法吗?
注意:我用于实际工作的分割模式有点复杂,当然不像上面的例子那样是常量。因此,简单地插入交替的常量值(或压缩它们)是不够的。
更新这是一个更具代表性的正则表达式
val str = "Here is some stuff PAT and second token PAT and third token
or something else and fourth"
val r = "(PAT|something else)".r
r.split(str)
res14: Array[String] = Array("Here is some stuff ", " and second token ", "
and third token ", " and fourth")
答案 0 :(得分:3)
对于不涉及无限宽度图案的非复杂图案,您可以使用lookbehind / lookahead解决方案:
val str = "Here is some stuff PAT and second token PAT and third token PAT and fourth"
val r = "((?<=PAT)|(?=PAT))".r
print(r.split(str).toList)
sample demo的输出:List(Here is some stuff , PAT, and second token , PAT, and third token , PAT, and fourth)
这个想法只是为了匹配(?<=PAT)
之前和(?=PAT)
PAT
模式之后的空字符串,并且只在那里进行分割。不幸的是,没有像使用带有捕获组的正则表达式拆分这样的便利功能,并将捕获的文本保留为结果数组/列表的元素。
作为替代方案,应使用匹配正则表达式与findAllIn
。或者可以创建分隔模式前面或末尾的临时单字符分隔符以进一步分割它们。