2017-12-03 5 views
0

Ich habe folgende EingabezeichenfolgenScala: Regex Pattern Matching

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

Ich mag würde das Folgende als Ausgangs

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

Ich habe versucht, die folgenden

StandardTokenParsers erhalten

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] 
^ 

RegEx

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 

Kann jemand bitte helfen? Vielen Dank!

Antwort

0

Ihr Muster sieht wie /(desired-group1)/(desired-group2)?XXX=(desired-group3) aus.

So würde regex

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

note sein - escape ? char.

Wie es funktionieren wird ist,

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

Nun gelten die Regex, die Sie die Gruppe aller gibt Spiele

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

Da Sie nur Pflege kümmern uns um 2., 4. und 6. Spiel, sammle nur diese.

So ist die Lösung wie, aussehen würde

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=) 

Wenn Sie Ihre Eingabe regex nicht übereinstimmt, erhalten Sie leere Ergebnis

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

Arbeiten regex hier - https://regex101.com/r/HuGRls/1/