2

如何在 Scala 中获取字符串上的正则表达式匹配的索引?

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?

4

3 回答 3

3

Match类包含描述特定正则表达式匹配的属性,包括它开始的位置。

"foo".r.findFirstMatchIn(bar).map(_.start)应该做你问的东西。

但是如果你真的只是在寻找一个子字符串,那么bar.indexOf("foo")会快很多。

于 2018-11-30T22:10:51.057 回答
3

建立在 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()
于 2018-11-30T23:08:48.967 回答
1

Dima 和 jwvh 都有助于找到我需要的东西,尤其是Match类提供的功能。为了完整起见和未来的读者,这里是我用于从给定 index获取结果索引的解决方案,即观察以下行为的函数:

findIndexFromPosition(body, """\slong string""", 0) // Some(36)
findIndexFromPosition(body, """\slong string""", 37) // None

首先使用JavaPatternMatcher类,按照这个答案

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)
于 2018-12-01T11:40:02.303 回答