Scala字符串中的查找模式

String上调用.r方法可以创建一个Regex对象,之后在查找是否含有一个匹配时就可以用findFirstIn,当需要查找是否完全匹配时可以使用findAllIn,eg.

    val numPattern = "[0-9]+".r
    val address = "zhengfangzhonglu 888hao"
    println(numPattern.findFirstIn(address))
    println(numPattern.findAllIn(address))

输出如下:

Some(888)
non-empty iterator

注意findFirstIn返回的是Option[String]类型的对象;findAllIn返回的是一个MatchIterator迭代器,可以对接过进行遍历;eg.

    val matches = numPattern.findAllIn(address)
    matches.foreach(println)

返回如下:

888

如果findAllIn方法没有找到任何结果,会返回一个空的迭代器,所以可以不用考虑是否需要判断结果为null之类的事情;如果想返回一个Array,可以在findAllIn之后调用toArray,eg.

    val matches = numPattern.findAllIn(address).toArray
    matches.foreach(println)

输出结果同上;
如果匹配失败,这种方式会返回一个空的数组,其他方法如toListtoSeq等都可以使用;

字符串.r源码解析

 /** You can follow a string with `.r`, turning it into a `Regex`. E.g.
   *
   *  `"""A\w*""".r`   is the regular expression for identifiers starting with `A`.
   */
  def r: Regex = r()

  /** You can follow a string with `.r(g1, ... , gn)`, turning it into a `Regex`,
   *  with group names g1 through gn.
   *
   *  `"""(\d\d)-(\d\d)-(\d\d\d\d)""".r("month", "day", "year")` matches dates
   *  and provides its subcomponents through groups named "month", "day" and
   *  "year".
   *
   *  @param groupNames The names of the groups in the pattern, in the order they appear.
   */
  def r(groupNames: String*): Regex = new Regex(toString, groupNames: _*)

这个相当于用那个字符串创建了一个Regex对象。

你可能感兴趣的:(Scala字符串中的查找模式)