Scala Regex Pattern Matching -
i need use regex match pattern in scala , have regex
inputpattern: scala.util.matching.regex = put (.*) in (.*) when run follwing happens:
scala> val inputpattern(verb, item, prep, obj) = "put in b"; scala.matcherror: put in b (of class java.lang.string) ... 33 elided i end verb("put"), item("a"), prep("in"), , obj("b") input "put in b" , verb("put"), item(""), prep("in"), , obj("") input "put in".
thanks
this works special cases :
scala> val inputpattern = "(put) (.*?) ?(in) ?(.*?)".r inputpattern: scala.util.matching.regex = (put) (.*) ?(in) ?(.*) scala> val inputpattern(verb, item, prep, obj) = "put in b" verb: string = put item: string = prep: string = in obj: string = b scala> val inputpattern(verb, item, prep, obj) = "put in" verb: string = put item: string = "" prep: string = in obj: string = "" put , in here captured in groups participate in pattern matching. used lazy regexps (.*?) capture less possible, may replace (\s*). ? gives optional space match "put in" (with 1 space between put , in , no space @ end).
but aware of this:
scala> val inputpattern(verb, item, prep, obj) = "put ainb" verb: string = put item: string = prep: string = in obj: string = b scala> val inputpattern(verb, item, prep, obj) = "put aininb" verb: string = put item: string = prep: string = in obj: string = inb scala> val inputpattern(verb, item, prep, obj) = "put ain" verb: string = put item: string = prep: string = in obj: string = "" if have simple command interpreter may good, otherwise should match special cases separately.
to process simple (not natural) language, may consider standardtokenparsers, context-free (chomsky type 2):
import scala.util.parsing.combinator.syntactical._ val p = new standardtokenparsers { lexical.reserved ++= list("put", "in") def p = "put" ~ opt(ident) ~ "in" ~ opt(ident) } scala> p.p(new p.lexical.scanner("put in b")) warning: there 1 feature warning; re-run -feature details res13 = [1.11] parsed: (((put~some(a))~in)~some(b)) scala> p.p(new p.lexical.scanner("put in")) warning: there 1 feature warning; re-run -feature details res14 = [1.7] parsed: (((put~none)~in)~none)
Comments
Post a Comment