如何获取Scala中String上的正则表达式匹配的索引?
val body = "This is a 'long string' with long string in it."
println(body.indexOf("long string")) // 11
println(body.indexOf("long string", 12)) // 37
// I'm looking for something like this:
"""\slong string""".r.findIndexIn(body) // Should give Some(36)
"""\slong string""".r.findIndexIn(body, 37) // Should give None
是否有一些简单的方法可以不循环查找s"^${myRegex}"
的字符?还是我需要使用Java?
答案 0 :(得分:1)
Match
类包含描述特定正则表达式匹配的属性,包括它开始的位置。
"foo".r.findFirstMatchIn(bar).map(_.start)
之类的东西应该可以满足您的要求。
但是,如果您真的只是在寻找子字符串,那么bar.indexOf("foo")
会更快。
答案 1 :(得分:1)
以Dima的正确答案为基础:您只需通过目标字符串即可获得所有匹配索引的列表。
"""\slong string""".r.findAllMatchIn(body).map(_.start).toList //List(28)
""".long string""" .r.findAllMatchIn(body).map(_.start).toList //List(10, 28)
"""Xlong string""" .r.findAllMatchIn(body).map(_.start).toList //List()
答案 2 :(得分:1)
Dima和jwvh都有助于找到我需要的东西,特别是Match
类提供的功能。为了完整起见并为将来的读者所用,以下是我用于从给定索引中获取结果的索引的解决方案,即一种观察以下行为的函数:
findIndexFromPosition(body, """\slong string""", 0) // Some(36)
findIndexFromPosition(body, """\slong string""", 37) // None
首先按照this answer使用Java的Pattern
和Matcher
类:
def findIndexFromPosition(body: String, pattern: String, fromIndex: Int): Option[Int] = {
val regex = Pattern.compile("\\slong string\\s").matcher(body)
regex.find(fromIndex) match {
case true => Some(regex.end)
case false => None
}
}
并且,在jwvh的回答的帮助下,采用了更具Scalamatic的方式:
"""\slong string""".r.findAllMatchIn(body).map(_.start).find(_ > fromIndex)