2017-04-24 6 views
3

나는 내가 정의 된 견인 정규식 패턴 중 하나와 일치 문자열의 일부를 추출 할 :패턴 일치 추출물 문자열 스칼라

val matcher= (s:String) => s match {case pPat(el)=> println(el) // print the P.25.01.25 
             case rPat(el)=>println(el) // print R0100 
             case _ => println("no match")} 
: 지금과 같은 요소를 추출하는 나의 방법을 정의

//should match R0010, R0100,R0300 etc 
    val rPat="[R]{1}[0-9]{4}".r 
    // should match P.25.01.21 , P.27.03.25 etc 
    val pPat="[P]{1}[.]{1}[0-9]{2}[.]{1}[0-9]{2}[.]{1}[0-9]{2}".r 

그리고 테스트 예와 함께 : 나는 정규식 표현이 잘못 있는지 확실하지 않습니다하지만

val pSt=" P.25.01.21 - Hello whats going on?" 
    matcher(pSt)//prints "no match" but should print P.25.01.21 
    val rSt= "R0010 test test 3,870" 
    matcher(rSt) //prints also "no match" but should print R0010 
    //check if regex is wrong 
    val pHead="P.25.01.21" 
    pHead.matches(pPat.toString)//returns true 
    val rHead="R0010" 
    rHead.matches(rPat.toString)//return true 

일치하는 방법 작품 요소에. 그렇다면이 접근 방식의 문제점은 무엇입니까?

답변

2

당신이 패턴 문자열 일치 사용 유념해야한다 :

  • 는 전체 일치해야합니다 전달하는 .r 패턴 문자열이 없으면 일치 항목이 반환되지 않습니다. (해결 방법은 입니다.
  • 원치 않은 일치 항목을 찾은 후에는을주의해야합니다.가 match 블록 내부
  • (솔루션은 실제 요구 사항은 일반적으로 단어 \blookarounds 충분, 또는 음 사용할 수 있습니다 경계 무엇인지에 따라 다릅니다) CSR123456에서 R1234을 일치, 정규식 매칭 기능이 될 수있는 캡처 그룹이 필요합니다 현재 가치를 되찾고 싶다면 을 pPat(el)rPat(el)으로 정의하십시오. 패턴에

    val pSt=" P.25.01.21 - Hello whats going on?" 
    matcher(pSt) // => P.25.01.21 
    val pSt2_bad=" CP.2334565.01124.212 - Hello whats going on?" 
    matcher(pSt2_bad) // => no match 
    val rSt= "R0010 test test 3,870" 
    matcher(rSt) // => R0010 
    val rSt2_bad = "CSR00105 test test 3,870" 
    matcher(rSt2_bad) // => no match 
    

    일부 메모를 다음

    val rPat="""\b(R\d{4})\b""".r.unanchored 
    val pPat="""\b(P\.\d{2}\.\d{2}\.\d{2})\b""".r.unanchored 
    
    val matcher= (s:String) => s match {case pPat(el)=> println(el) // print the P.25.01.25 
        case rPat(el)=>println(el) // print R0100 
        case _ => println("no match") 
    } 
    

    :

그래서, 나는 following solution 제안

  • \b - 선도적 인 단어 경계
  • (R\d{4}) - 정확히 4 자리
  • \b 일치 캡처 그룹 - 후행 단어 경계

인해 리터럴 문자열을 정의하는 데 사용되는 삼중 따옴표로는 백 슬래시를 이스케이프 할 필요가 없습니다.

1

은 패턴 그룹을 소개 :

val rPat=".*([R]{1}[0-9]{4}).*".r 

val pPat=".*([P]{1}[.]{1}[0-9]{2}[.]{1}[0-9]{2}[.]{1}[0-9]{2}).*".r 

... 

scala> matcher(pSt) 
P.25.01.21 

scala> matcher(rSt) 
R0010 
+0

감사합니다. –

0

코드가 다음과 같이 작성되면 원하는 결과가 생성됩니다. 다음 참조 API 설명서는 http://www.scala-lang.org/api/2.12.1/scala/util/matching/Regex.html

//should match R0010, R0100,R0300 etc 
    val rPat="[R]{1}[0-9]{4}".r 
    // should match P.25.01.21 , P.27.03.25 etc 
    val pPat="[P]{1}[.]{1}[0-9]{2}[.]{1}[0-9]{2}[.]{1}[0-9]{2}".r 


    def main(args: Array[String]) { 
    val pSt=" P.25.01.21 - Hello whats going on?" 
    val pPatMatches = pPat.findAllIn(pSt); 
    pPatMatches.foreach(println) 
    val rSt= "R0010 test test 3,870" 
    val rPatMatches = rPat.findAllIn(rSt); 
    rPatMatches.foreach(println) 

    } 

, 그런 당신을 위해 작동하는지 알려 주시기 바랍니다 있습니다.