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)
输出结果同上;
如果匹配失败,这种方式会返回一个空的数组,其他方法如toList
,toSeq
等都可以使用;
字符串.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
对象。
网友评论