-
Notifications
You must be signed in to change notification settings - Fork 7
정규 표현식과 일치시키키
no-t edited this page Aug 29, 2016
·
1 revision
// src/main/scala/progscala2/patternmatching/match-regex.sc
val BookExtractorRE = """Book: title=([^,]+),\s+author=(.+)""".r // <1>
val MagazineExtractorRE = """Magazine: title=([^,]+),\s+issue=(.+)""".r
val catalog = Seq(
"Book: title=Programming Scala Second Edition, author=Dean Wampler",
"Magazine: title=The New Yorker, issue=January 2014",
"Unknown: text=Who put this here??"
)
for (item <- catalog) {
item match {
case BookExtractorRE(title, author) => // <2>
println(s"""Book "$title", written by $author""")
case MagazineExtractorRE(title, issue) =>
println(s"""Magazine "$title", issue $issue""")
case entry => println(s"Unrecognized entry: $entry")
}
}
포획그룹 capture group 이 둘 있다. 첫번째는 제목을 잡아내고 두번째는 작가를 잡는다 r 메서드를 문자열에 대해 호출하면 정규표현식 객체(scala.util.matching.Regex 타입)을 만든다
val BookExtractorRE = """Book: title=([^,]+),\s+author=(.+)""".r // <1>
item match {
case BookExtractorRE(title, author) => // <2>
println(s"""Book "$title", written by $author""")
case MagazineExtractorRE(title, issue) =>
println(s"""Magazine "$title", issue $issue""")
case entry => println(s"Unrecognized entry: $entry")
}
val MagazineExtractorRE = """Magazine: title=([^,]+),\s+issue=(.+)""".r
val MagazineExtractorRE = "Magazine: title=([^,]+),\\s+issue=(.+)".r
val MagazineExtractorRE = new scala.util.matching.Regex("""Magazine: title=([^,]+),\s+issue=(.+)""")
val matchTxt = "title"
val MagazineExtractorRE = s"""Magazine: $matchTxt=([^,]+),\\s+issue=(.+)""".r