2017-12-03 5 views
0

I가 I는 I 다음스칼라 : 정규식 패턴 매칭

StandardTokenParsers 시도

"horses", "c132", "[email protected]" 
"Goats", "b-01", "[email protected]" 
"CATS", "001", "[email protected]" 

출력으로서 다음 획득하려는

"/horses/[email protected]" 
"/Goats/[email protected]" 
"/CATS/[email protected]" 

다음 입력 문자열

import scala.util.parsing.combinator.syntactical._ 
val p = new StandardTokenParsers { 
lexical.reserved ++= List("/", "?", "XXX=") 
def p = "/" ~ opt(ident) ~ "/" ~ opt(ident) ~ "?" ~ "XXX=" ~ opt(ident) 
} 
p: scala.util.parsing.combinator.syntactical.StandardTokenParsers{def p: this.Parser[this.~[this.~[this.~[String,Option[String]],String],Option[String]]]} = [email protected] 

scala> p.p(new p.lexical.Scanner("/horses/[email protected]")) 
warning: there was one feature warning; re-run with -feature for details 
res3: p.ParseResult[p.~[p.~[p.~[String,Option[String]],String],Option[String]]] = 
[1.1] failure: ``/'' expected but ErrorToken(illegal character) found 

/horses/[email protected] 
^ 
,210

정규식

import scala.util.matching.regex 
val p1 = "(/)(.*)(/)(.*)(?)(XXX)(=)(.*)".r 
p1: scala.util.matching.Regex = (/)(.*)(/)(.*)(?)(XXX)(=)(.*) 

scala> val p1(_,animal,_,id,_,_,_,company) = "/horses/[email protected]" 
scala.MatchError: /horses/[email protected] (of class java.lang.String) 
    ... 32 elided 

누군가가 도와 주실 수 있습니까? 감사!

답변

0

귀하의 패턴은 /(desired-group1)/(desired-group2)?XXX=(desired-group3)입니다.

그래서, 정규식

scala> val extractionPattern = """(/)(.*)(/)(.*)(\?XXX=)(.*)""".r 
extractionPattern: scala.util.matching.Regex = (/)(.*)(/)(.*)(\?XXX=)(.*) 

참고 것 - ? 문자를 탈출. 만 2, 4 및 대한 개호 때문에 작동하는 것입니다 것입니다 방법

지금

Full match `/horses/[email protected]` 
Group 1. `/` 
Group 2. `horses` 
Group 3. `/` 
Group 4. `c132` 
Group 5. `?XXX=` 
Group 6. `[email protected]` 

, 당신에게 모든 그룹을주는 정규식을 적용은

scala> extractionPattern.findAllIn("""/horses/[email protected]""") 
         .matchData.flatMap{m => m.subgroups}.toList 
res15: List[String] = List(/, horses, /, c132, ?XXX=, [email protected]) 

일치 여섯 번째 경기, 오직 그들을 수집합니다. 귀하의 의견이 정규식과 일치하지 않는 경우

그래서 솔루션의 모습은,

scala> extractionPattern.findAllIn("""/horses/[email protected]""") 
         .matchData.map(_.subgroups) 
         .flatMap(matches => Seq(matches(1), matches(3), matches(4))).toList 
res16: List[String] = List(horses, c132, ?XXX=) 

, 당신은 여기에 빈 결과를

scala> extractionPattern.findAllIn("""/horses/c132""") 
         .matchData.map(_.subgroups) 
         .flatMap(matches => Seq(matches(1), matches(3), matches(4))).toList 
res17: List[String] = List() 

근무 정규식을 얻을 - https://regex101.com/r/HuGRls/1/