수색…


통사론

  • re.findAllIn (s : CharSequence) : MatchIterator
  • re.findAllMatchIn (s : CharSequence) : 반복자 [일치]
  • re.findFirstIn (s : CharSequence) : 옵션 [문자열]
  • re.findFirstMatchIn (s : CharSequence) : 옵션 [일치]
  • re.findPrefixMatchIn (s : CharSequence) : 옵션 [일치]
  • re.findPrefixOf (s : CharSequence) : 옵션 [문자열]
  • re.replaceAllIn (s : CharSequence, Replacer : Match => String) : String
  • re.replaceAllIn (s : CharSequence, replacement : String) : String
  • re.replaceFirstIn (s : CharSequence, replacement : String) : String
  • re.replaceSomeIn (s : CharSequence, Replacer : Match => Option [String]) : 문자열
  • re.split (s : CharSequence) : Array [문자열]

정규 표현식 선언

scala.collection.immutable.StringOps 를 통해 암시 적으로 제공되는 r 메서드는 제목 문자열에서 scala.util.matching.Regex 인스턴스를 생성합니다. 자바에서와 같이 백 슬래시를 이스케이프 할 필요가 없으므로 Scala의 삼중 인용 문자열 구문이 유용합니다.

val r0: Regex = """(\d{4})-(\d${2})-(\d{2})""".r     // :)
val r1: Regex = "(\\d{4})-(\\d{2})-(\\d{2})".r // :(

scala.util.matching.Regexjava.util.regex.Pattern에 대한 래퍼 (wrapper)로 Scala 용 관용적 인 정규 표현식 API를 구현하며 지원되는 구문은 동일합니다. 스칼라가 멀티 라인 문자열 리터럴을 지원했다는 사실은 x 플래그가 상당히 유용 해 주석을 허용하고 패턴 공백을 무시한다는 것을 의미합니다.

val dateRegex = """(?x:
   (\d{4}) # year
  -(\d{2}) # month
  -(\d{2}) # day
)""".r

오버로드 된 버전의 r , def r(names: String*): Regex 를 사용하면 패턴 캡처에 그룹 이름을 할당 할 수 있습니다. 이름이 캡처에서 분리되기 때문에 이것은 다소 부서지기 때문에 여러 위치에서 정규식을 사용하는 경우에만 사용해야합니다.

"""(\d{4})-(\d{2})-(\d{2})""".r("y", "m", "d").findFirstMatchIn(str) match {
  case Some(matched) =>
    val y = matched.group("y").toInt
    val m = matched.group("m").toInt
    val d = matched.group("d").toInt
    java.time.LocalDate.of(y, m, d)
  case None => ???
}

문자열의 패턴 일치 반복

val re = """\((.*?)\)""".r

val str = "(The)(example)(of)(repeating)(pattern)(in)(a)(single)(string)(I)(had)(some)(trouble)(with)(once)"

re.findAllMatchIn(str).map(_.group(1)).toList
res2: List[String] = List(The, example, of, repeating, pattern, in, a, single, string, I, had, some, trouble, with, once)


Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow