在两个标签之间查找文字

时间:2015-12-09 12:49:16

标签: regex scala

下面我尝试使用正则表达式<hr>.find1.<hr>查找两个<hr>标记之间的文本:

val line = "<hr>this is find1 the line 1 <hr> tester here <hr> this is a new line <hr>"
  val toFind = "<hr>.find1.<hr>".r
  println(toFind.findFirstIn(line))

输出应为:this is find1 the line 1

但是找不到文字。如何修改正则表达式来查找文本?

更新:要找到的元素可以位于List

中的任何位置

2 个答案:

答案 0 :(得分:1)

在字符串上使用split,如下所示,

line.trim.split("<hr>").dropWhile(_.isEmpty).take(1)
Array("this is find1 the line 1 ")

更新为了找到包含字符串的分区,请考虑这一点,

line.split("<hr>").find( _.contains("find1"))
Some(this is find1 the line 1 )

答案 1 :(得分:1)

另一种方法是合并inverse matching和懒惰匹配

val toFind = "<hr>(((?!<hr>).)*find1.*?)<hr>".r
println(toFind.findFirstMatchIn(line).map(_.group(1)))