Scala中,正则表达式和Java类似,具体可以参考java.util.regex.Pattern
Scala中,正则表达式类为scala.util.matching.Regex
其中,Regex也可以用正则表达式字符串.r方式来构造,示例如下:
scala> import scala.util.matching.Regex
import scala.util.matching.Regex
scala> val Decimal = new Regex("(-)?(\\d+)(\\.\\d*)?")
Decimal: scala.util.matching.Regex = (-)?(\d+)(\.\d*)?
scala> val Decimal = """()?(\d+)(\.\d*)?""".r
Decimal: scala.util.matching.Regex = ()?(\d+)(\.\d*)?
Regex常用的方法有:
findFirstIn、findAllIn、findPrefixOf
示例如下:
scala> val str = "0.12 is greater than 0.01"
str: String = 0.12 is greater than 0.01
scala> Decimal.findFirstIn(str)
res10: Option[String] = Some(0.12)
scala> for(i <- Decimal.findAllIn(str)) println(i)
0.12
0.01
scala> Decimal.findPrefixOf(str)
res13: Option[String] = Some(0.12)
参考自:
Programming Scala 2nd Edition
阅读(1447) | 评论(0) | 转发(0) |