Last active
February 1, 2016 05:29
-
-
Save Centaur/f3c836f3fdcf14833f0b to your computer and use it in GitHub Desktop.
find by regex
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package org.snippets | |
object RegexMatch { | |
val LOCATION_JU_MAIN_CAT_PREFIX = "a" | |
val LOCATION_JU_WAP_CAT_PREFIX = "b" | |
val LOCATION_JU_TAOBAO_CAT_PREFIX = "c" | |
val LOCATION_JU_TMALL_CAT_PREFIX = "d" | |
val juCatRE = s"$LOCATION_JU_MAIN_CAT_PREFIX([0-9]+)".r | |
val wapCatRE = s"$LOCATION_JU_WAP_CAT_PREFIX([0-9]+)".r | |
val taobaoCatRE = s"$LOCATION_JU_TAOBAO_CAT_PREFIX([0-9]+)".r | |
val tmallCatRE = s"$LOCATION_JU_TMALL_CAT_PREFIX([0-9]+)".r | |
def unapply(location: String): Option[Long] = | |
location match { | |
case juCatRE(catId) => Some(catId.toLong) | |
case wapCatRE(catId) => Some(catId.toLong) | |
case taobaoCatRE(catId) => Some(catId.toLong) | |
case tmallCatRE(catId) => Some(catId.toLong) | |
} | |
def fnd(location: String): Option[Long] = | |
Seq(juCatRE, wapCatRE, taobaoCatRE, tmallCatRE) | |
.flatMap(_.unapplySeq(location)) | |
.headOption | |
.map(_.head.toLong) | |
def main(args: Array[String]) { | |
assert(RegexMatch.unapply("a123").contains(123)) | |
assert(RegexMatch.fnd("a123").contains(123)) | |
assert(RegexMatch.fnd("b3").contains(3)) | |
assert(RegexMatch.fnd("b").isEmpty) | |
assert(RegexMatch.fnd("a123b").isEmpty) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment