代码之家  ›  专栏  ›  技术社区  ›  Druckles

获取scala中regex匹配的索引

  •  0
  • Druckles  · 技术社区  · 6 年前

    如何获取scala中字符串的regex匹配的索引?

    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?

    3 回复  |  直到 6 年前
        1
  •  1
  •   Dima    6 年前

    Match 类包含描述特定regex匹配的属性,包括它开始的位置。

    类似的东西 "foo".r.findFirstMatchIn(bar).map(_.start) 应该按你的要求去做。

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

        2
  •  1
  •   jwvh    6 年前

    建立在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()
    
        3
  •  1
  •   Druckles    6 年前

    dima和jvh都有助于找到我需要的东西,特别是 Match 班级。为了完整性和将来的读者,下面是我用来获取结果索引的解决方案 从给定索引 即观察以下行为的函数:

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

    首先使用Java Pattern Matcher 类,按 this answer :

    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的回答的帮助下,更具规模的方法是:

    """\slong string""".r.findAllMatchIn(body).map(_.start).find(_ > fromIndex)
    
    推荐文章