반응형
정규식을 사용하는 Scala 캡처 그룹
이 코드가 있다고 가정 해 봅시다.
val string = "one493two483three"
val pattern = """two(\d+)three""".r
pattern.findAllIn(string).foreach(println)
나는 findAllIn
반환 만 기대 483
했지만 대신 반환했습니다 two483three
. unapply
해당 부분 만 추출 하는 데 사용할 수 있다는 것을 알고 있지만 전체 문자열에 대한 패턴이 있어야합니다.
val pattern = """one.*two(\d+)three""".r
val pattern(aMatch) = string
println(aMatch) // prints 483
java.util
직접 클래스를 사용하지 않고 unapply를 사용 하지 않고 이것을 달성하는 다른 방법이 있습니까?
다음 group(1)
은 각 경기에 액세스 할 수있는 방법의 예입니다 .
val string = "one493two483three"
val pattern = """two(\d+)three""".r
pattern.findAllIn(string).matchData foreach {
m => println(m.group(1))
}
이것은 "483"
( ideone.com에서 볼 수 있듯이) 인쇄 됩니다 .
둘러보기 옵션
패턴의 복잡성에 따라 둘러보기를 사용하여 원하는 부분 만 일치 시킬 수도 있습니다 . 다음과 같이 보일 것입니다.
val string = "one493two483three"
val pattern = """(?<=two)\d+(?=three)""".r
pattern.findAllIn(string).foreach(println)
위의 내용도 인쇄됩니다 "483"
( ideone.com에서 볼 수 있음 ).
참고 문헌
val string = "one493two483three"
val pattern = """.*two(\d+)three.*""".r
string match {
case pattern(a483) => println(a483) //matched group(1) assigned to variable a483
case _ => // no match
}
을 (를)보고 싶은데 group(1)
, 현재 group(0)
"전체 일치 문자열"을보고 있습니다.
이 정규식 자습서를 참조하십시오 .
시작 Scala 2.13
정규식 솔루션에 대한 대안으로,이 패턴 일치 a를 수도 String
로 문자열 보간을 unapplying :
"one493two483three" match { case s"${x}two${y}three" => y }
// String = "483"
또는:
val s"${x}two${y}three" = "one493two483three"
// x: String = one493
// y: String = 483
일치하지 않는 입력이 예상되는 경우 기본 패턴 가드를 추가 할 수 있습니다.
"one493deux483three" match {
case s"${x}two${y}three" => y
case _ => "no match"
}
// String = "no match"
def extractFileNameFromHttpFilePathExpression(expr: String) = {
//define regex
val regex = "http4.*\\/(\\w+.(xlsx|xls|zip))$".r
// findFirstMatchIn/findAllMatchIn returns Option[Match] and Match has methods to access capture groups.
regex.findFirstMatchIn(expr) match {
case Some(i) => i.group(1)
case None => "regex_error"
}
}
extractFileNameFromHttpFilePathExpression(
"http4://testing.bbmkl.com/document/sth1234.zip")
참고 URL : https://stackoverflow.com/questions/3050907/scala-capture-group-using-regex
반응형
'Nice programing' 카테고리의 다른 글
C ++ : 임시 인수의 수명? (0) | 2020.11.23 |
---|---|
jQuery : 속성이 값보다 큰 모든 요소 선택 (0) | 2020.11.23 |
li : before {content : "■"; (0) | 2020.11.23 |
문자열에 오류 유형이 지정되지 않는 이유는 무엇입니까? (0) | 2020.11.23 |
배경 이미지 위에 CSS 그라데이션 사용 (0) | 2020.11.23 |