package com.aura.scala.day01 import scala.util.matching.Regex object regularExpressionPatterns { def main(args: Array[String]): Unit = { // example 1 // .r 方法可便任意字符串变成一个正则表达式 val numberPatter: Regex = "[0-9]".r numberPatter.findFirstMatchIn("dsafasdfasfasfas") match { case Some(_) => println("Password OK") case None => println("Password must contain a number") } // example 2 val KeyValPattern: Regex = "([0-9A-Za-z-#() ]+):([0-9A-Za-z-#() ]+)".r val input: String = """ |background-color: #A03300; |background-image: url(img/header100.png); |background-position: top center; |background-repeat: repeat-x; |background-size: 2160px 108px |margin: 0; |height: 108px; | 100%; """.stripMargin for( patternMath <- KeyValPattern.findAllMatchIn(input)) println(s"key:${patternMath.group(1)} value:${patternMath.group(2)}") } }
output:
"D:Program FilesJavajdk1.8.0_201injava.exe" "-javaagent:D:Program FilesJetBrainsIntelliJ IDEA 2019.1.3libidea_rt.jar=8599:D:Program FilesJetBrainsIntelliJ IDEA 2019.1.3in" -Dfile.encoding=UTF-8 -classpath "D:Program FilesJavajdk1.8.0_201jrelibcharsets.jar;D:Program FilesJavajdk1.8.0_201jrelibdeploy.jar;D:Program FilesJavajdk1.8.0_201jrelibextaccess-bridge-64.jar;D:Program FilesJavajdk1.8.0_201jrelibextcldrdata.jar;D:Program FilesJavajdk1.8.0_201jrelibextdnsns.jar;D:Program FilesJavajdk1.8.0_201jrelibextjaccess.jar;D:Program FilesJavajdk1.8.0_201jrelibextjfxrt.jar;D:Program FilesJavajdk1.8.0_201jrelibextlocaledata.jar;D:Program FilesJavajdk1.8.0_201jrelibext ashorn.jar;D:Program FilesJavajdk1.8.0_201jrelibextsunec.jar;D:Program FilesJavajdk1.8.0_201jrelibextsunjce_provider.jar;D:Program FilesJavajdk1.8.0_201jrelibextsunmscapi.jar;D:Program FilesJavajdk1.8.0_201jrelibextsunpkcs11.jar;D:Program FilesJavajdk1.8.0_201jrelibextzipfs.jar;D:Program FilesJavajdk1.8.0_201jrelibjavaws.jar;D:Program FilesJavajdk1.8.0_201jrelibjce.jar;D:Program FilesJavajdk1.8.0_201jrelibjfr.jar;D:Program FilesJavajdk1.8.0_201jrelibjfxswt.jar;D:Program FilesJavajdk1.8.0_201jrelibjsse.jar;D:Program FilesJavajdk1.8.0_201jrelibmanagement-agent.jar;D:Program FilesJavajdk1.8.0_201jrelibplugin.jar;D:Program FilesJavajdk1.8.0_201jrelib esources.jar;D:Program FilesJavajdk1.8.0_201jrelib t.jar;C:UsersadminIdeaProjectsScalaDayoutproductionScalaDay;C:Program Files (x86)scalalibscala-actors-2.11.0.jar;C:Program Files (x86)scalalibscala-actors-migration_2.11-1.1.0.jar;C:Program Files (x86)scalalibscala-library.jar;C:Program Files (x86)scalalibscala-parser-combinators_2.11-1.0.4.jar;C:Program Files (x86)scalalibscala-reflect.jar;C:Program Files (x86)scalalibscala-swing_2.11-1.0.2.jar;C:Program Files (x86)scalalibscala-xml_2.11-1.0.4.jar" com.aura.scala.day01.regularExpressionPatterns Password must contain a number key:background-color value: #A03300 key:background-image value: url(img key:background-position value: top center key:background-repeat value: repeat-x key:background-size value: 2160px 108px key:margin value: 0 key:height value: 108px key:width value: 100