많은 문자열을 일치시키고 싶은 정규식 패턴이 있다고 가정합니다.
val Digit = """\d""".r
주어진 문자열이 정규식과 완전히 일치하는지 확인하고 싶습니다. Scala에서 이것을 수행하는 좋고 관용적 인 방법은 무엇입니까?
정규식에서 패턴 일치를 수행 할 수 있다는 것을 알고 있지만 추출 할 그룹이 없기 때문에이 경우 구문 상별로 만족스럽지 않습니다.
scala> "5" match { case Digit() => true case _ => false }
res4: Boolean = true
또는 기본 Java 패턴으로 돌아갈 수 있습니다.
scala> Digit.pattern.matcher("5").matches
res6: Boolean = true
우아하지도 않습니다.
더 나은 해결책이 있습니까?
답변
내 질문에 답하기 위해 “포주 내 라이브러리 패턴”을 사용하겠습니다.
object RegexUtils {
implicit class RichRegex(val underlying: Regex) extends AnyVal {
def matches(s: String) = underlying.pattern.matcher(s).matches
}
}
이렇게 사용하세요
import RegexUtils._
val Digit = """\d""".r
if (Digit matches "5") println("match")
else println("no match")
누군가가 더 나은 (표준) 솔루션을 제시하지 않는 한.
메모
-
나는
String
잠재적 인 부작용의 범위를 제한 하지 않았습니다 . -
unapplySeq
그 맥락에서 잘 읽히지 않습니다.
답변
저는 Scala를 잘 모르지만 다음과 같이 할 수 있습니다.
"5".matches("\\d")
참고 문헌
답변
전체 일치를 위해 unapplySeq를 사용할 수 있습니다 . 이 메서드는 대상 (전체 일치) 일치를 시도하고 일치 항목을 반환합니다.
scala> val Digit = """\d""".r
Digit: scala.util.matching.Regex = \d
scala> Digit unapplySeq "1"
res9: Option[List[String]] = Some(List())
scala> Digit unapplySeq "123"
res10: Option[List[String]] = None
scala> Digit unapplySeq "string"
res11: Option[List[String]] = None
답변
"""\d""".r.unapplySeq("5").isDefined //> res1: Boolean = true
"""\d""".r.unapplySeq("a").isDefined //> res2: Boolean = false
답변
대답은 정규식에 있습니다.
val Digit = """^\d$""".r
그런 다음 기존 방법 중 하나를 사용하십시오.
답변
표준 Scala 라이브러리와 미리 컴파일 된 정규식 패턴 및 패턴 일치 (Scala 최첨단) 사용 :
val digit = """(\d)""".r
"2" match {
case digit( a) => println(a + " is Digit")
case _ => println("it is something else")
}
더 읽을 거리 : http://www.scala-lang.org/api/2.12.1/scala/util/matching/index.html
답변
