• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Scala RegexParsers类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Scala中scala.util.parsing.combinator.RegexParsers的典型用法代码示例。如果您正苦于以下问题:Scala RegexParsers类的具体用法?Scala RegexParsers怎么用?Scala RegexParsers使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了RegexParsers类的18个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。

示例1: Parser

//设置package包名称以及导入依赖的类
package mctt

import scala.util.parsing.combinator.RegexParsers
import mctt.preprocessing.{LabelCollector, LabelAnnotator}

class Parser extends RegexParsers {
  def task: Parser[Task] = """[I|A]""".r ~ "_" ~ """[a-zA-Z0-9]+""".r ^^ { 
    case i ~ s ~ s2 => Task({if (i == "I") TaskType.Interaction else TaskType.Application}, s2) 
  }

  def all: Parser[All] = "all" ~> devlist ~ ("(" ~> expr <~ ")") ^^ {
    case dl ~ e1 => All(e1, dl)
  }

  def any: Parser[Any] = "any" ~> devlist ~ ("(" ~> expr <~ ")") ^^ {
    case dl ~ e1 => Any(e1, dl)
  }
  
  def devlist: Parser[List[String]] = dev*

  def dev: Parser[String] = "_"~"""[a-zA-Z0-9]+""".r  ^^ { case s1 ~ s2 => s2 }
  
  def choice: Parser[Choice] = "choice" ~ "(" ~> expr ~ ("," ~> expr <~ ")") ^^ {
    case e1 ~ e2 => Choice(e1, e2)
  }

  def disabling: Parser[Disabling] = "disabling" ~ "(" ~> expr ~ ("," ~> expr <~ ")") ^^ {
    case e1 ~ e2 => Disabling(e1, e2)
  }
  
  def reset: Parser[Reset] = "reset" ~ "(" ~> expr ~ ("," ~> expr <~ ")") ^^ {
    case e1 ~ e2 => Reset(e1, e2)
  }
  
  def repeat: Parser[Repeat] = "repeat" ~ "(" ~> expr <~ ")" ^^ {
    case e1 => Repeat(e1)
  } 
  
  def enabling: Parser[Enabling] = "enabling" ~ "(" ~> expr ~ ("," ~> expr <~ ")") ^^ {
    case e1 ~ e2 => Enabling(e1, e2)
  }

  def concurrent: Parser[Concurrent] = "concurrent" ~ "(" ~> expr ~ ("," ~> expr <~ ")") ^^ {
    case e1 ~ e2 => Concurrent(e1, e2)
  }
  
  def expr: Parser[Expr] = (all | any | choice | concurrent | disabling | reset | repeat | enabling | task)

  def eval(input: String) =
    parseAll(expr, input) match {
      case Success(result, _) => result
      case failure: NoSuccess => scala.sys.error(failure.msg)
    }
} 
开发者ID:MultiDeviceCTT,项目名称:MCTT,代码行数:55,代码来源:Parser.scala


示例2: FakeCompiler

//设置package包名称以及导入依赖的类
package codegen

import scala.util.parsing.combinator.RegexParsers
import java.io.{File, FileWriter, PrintWriter}
import org.apache.commons.io.FileUtils

object FakeCompiler {
  // This code will fail to compile with scala-2.10 (see https://issues.scala-lang.org/browse/SI-6189)
  case class ManyArgs(
    a1 : Int, a2: Int, a3 : Int, a4: Int, a5 : Int, a6: Int, a7 : Int, a8: Int, a9 : Int, a10: Int,
    a11 : Int, a12: Int, a13 : Int, a14: Int, a15 : Int, a16: Int, a17 : Int, a18: Int, a19 : Int, a20: Int,
    a21 : Int, a22: Int, a23 : Int, a24: Int, a25 : Int, a26: Int, a27 : Int, a28: Int, a29 : Int, a30: Int
                     )

  def main(args: Array[String]) = {
    println(ManyArgs(1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10))
    println("Running the fake compiler with argument " + args(0))

    object TestParser extends RegexParsers {
    }

    val outputFile = new File(args(0))
    FileUtils.forceMkdir(outputFile.getParentFile);
    val fileWriter = new PrintWriter(new FileWriter(outputFile))
    fileWriter.println("package generated")
    fileWriter.println("object Output { def main(args: Array[String]) = { println(\"Yay\") }}")

    println("Closing file " + args(0))
    fileWriter.close()
  }
} 
开发者ID:A1kmm,项目名称:sbt-mixversion-test,代码行数:32,代码来源:FakeCompiler.scala


示例3: ExerciseOne

//设置package包名称以及导入依赖的类
package chapter.nineteen

import scala.util.parsing.combinator.RegexParsers

object ExerciseOne {

  class ExprParser extends RegexParsers {
    val number = "[0-9.]+".r

    def expr: Parser[Double] = term ~ opt(("+" | "-") ~ expr) ^^ {
      case t ~ None => t
      case t ~ Some("+" ~ f) => t + f
      case t ~ Some("-" ~ f) => t - f
    }

    def term: Parser[Double] = factor ~ opt(("*" | "/" | "%") ~ term) ^^ {
      case f ~ None => f
      case f ~ Some("*" ~ t) => f * t
      case f ~ Some("/" ~ t) => f / t
      case f ~ Some("%" ~ t) => f % t
    }

    def factor: Parser[Double] = number ^^ { _.toDouble } | "(" ~> expr <~ ")"
  }

} 
开发者ID:deekim,项目名称:impatient-scala,代码行数:27,代码来源:ExerciseOne.scala


示例4: PostCompositionParser

//设置package包名称以及导入依赖的类
package org.phenoscape.kb.ingest.util

import scala.annotation.migration
import scala.collection.JavaConverters.setAsJavaSetConverter
import scala.util.parsing.combinator.RegexParsers

import org.apache.log4j.Logger 
import org.semanticweb.owlapi.apibinding.OWLManager
import org.semanticweb.owlapi.model.IRI
import org.semanticweb.owlapi.model.OWLClass
import org.semanticweb.owlapi.model.OWLClassExpression
import org.semanticweb.owlapi.model.OWLObjectProperty
import org.semanticweb.owlapi.model.OWLObjectSomeValuesFrom

object PostCompositionParser extends RegexParsers {

  private val factory = OWLManager.getOWLDataFactory

  def iri: Parser[IRI] = """[^\(\)\^]+""".r ^^ OBOUtil.iriForTermID

  def classIRI: Parser[OWLClass] = iri ^^ factory.getOWLClass

  def objectPropertyIRI: Parser[OWLObjectProperty] = iri ^^ factory.getOWLObjectProperty

  def conjunction: Parser[OWLClassExpression] = repsep(primary, "^") ^^ (in => in.size match {
    case 1 => in.head
    case _ => factory.getOWLObjectIntersectionOf(in.toSet.asJava)
  })
  
  def description: Parser[OWLClassExpression] = conjunction | primary

  def primary: Parser[OWLClassExpression] = someValuesFrom | classIRI

  def someValuesFrom: Parser[OWLObjectSomeValuesFrom] = objectPropertyIRI ~ ("(" ~> description <~ ")") ^^ {
    case prop ~ filler => factory.getOWLObjectSomeValuesFrom(prop, filler)
  }

  def parseExpression(expression: String): Option[OWLClassExpression] = {
    parseAll(conjunction, expression) match {
      case Success(result, remainder) => Option(result)
      case NoSuccess(message, remainder) => {
        logger.error("Failed to parse class expression: " + message)
        None
      }
    }
  }

  lazy val logger = Logger.getLogger(this.getClass)

} 
开发者ID:phenoscape,项目名称:phenoscape-kb-ingest,代码行数:51,代码来源:PostCompositionParser.scala


示例5: Markup

//设置package包名称以及导入依赖的类
package com.todesking.platebuilder

import scala.util.parsing.combinator.RegexParsers

sealed abstract class Markup {
}
object Markup {
  case class Plain(text: String) extends Markup
  case class UD(upper: Option[Markup], downer: Option[Markup]) extends Markup
  case class Group(elements: Seq[Markup]) extends Markup
  case class Bold(element: Markup) extends Markup

  def parse(s: String): Group = Parser.parse(s)

  object Parser extends RegexParsers {
    def parse(s: String): Group = Group(parse(markup, s).get)

    override def skipWhitespace = false

    def markup: Parser[Seq[Markup]] = rep(single)
    def single: Parser[Markup] = plain | sup | sub | group | command
    def command: Parser[Markup] = "\\" ~> """[a-zA-Z0-9_]+""".r ~ group ^^ {
      case "bf" ~ grp => Bold(grp)
      case unk => throw new RuntimeException(s"Unknown command: \\$unk")
    }
    def group: Parser[Group] = "{" ~> (rep(single) ^^ Group.apply) <~ "}"
    def plain: Parser[Plain] = rep1(plainChar) ^^ { chars => Plain(chars.mkString("")) }
    def plainChar: Parser[Char] = ("""\\[{}]""".r ^^ { s => s.charAt(1) }) | ("""[^^_{}\\]""".r ^^ { s => s.charAt(0) })
    def sup: Parser[Markup] = sup0 ~ sub0.? ^^ { case u ~ d => UD(Some(u), d) }
    def sub: Parser[Markup] = sub0 ~ sup0.? ^^ { case d ~ u => UD(u, Some(d)) }
    def sup0: Parser[Markup] = "^" ~> (plainChar ^^ { c => Plain(c.toString) } | group)
    def sub0: Parser[Markup] = "_" ~> (plainChar ^^ { c => Plain(c.toString) } | group)
  }
} 
开发者ID:todesking,项目名称:platebuilder,代码行数:35,代码来源:Markup.scala


示例6: MongoClientUriParser

//设置package包名称以及导入依赖的类
package com.github.jeroenr.tepkin

import java.net.InetSocketAddress

import scala.util.parsing.combinator.RegexParsers

object MongoClientUriParser extends RegexParsers {
  def credential: Parser[String] = """[^:@?]+""".r ^^ {
    _.toString
  }

  def hostName: Parser[String] = """[^:,?/]+""".r ^^ {
    _.toString
  }

  def port: Parser[Int] = """[0-9]+""".r ^^ {
    _.toInt
  }

  def database: Parser[String] = """[^?]+""".r ^^ {
    _.toString
  }

  def option: Parser[(String, String)] = """[^=]+""".r ~ "=" ~ """[^&]+""".r ^^ {
    case key ~ _ ~ value => key -> value
  }

  def options: Parser[Map[String, String]] = option ~ rep("&" ~ option) ^^ {
    case head ~ tail => (head +: tail.map(_._2)).toMap
  }

  def credentials: Parser[MongoCredentials] = credential ~ opt(":" ~ credential) ^^ {
    case username ~ None =>
      MongoCredentials(username = username)
    case username ~ Some(":" ~ password) =>
      MongoCredentials(username = username, password = Some(password))
  }

  def host: Parser[InetSocketAddress] = hostName ~ opt(":" ~ port) ^^ {
    case hostName ~ None => new InetSocketAddress(hostName, 27017)
    case hostName ~ Some(":" ~ port) => new InetSocketAddress(hostName, port)
  }

  def uri: Parser[MongoClientUri] = {
    "mongodb://" ~ opt(credentials ~ "@") ~ host ~ rep("," ~ host) ~ opt("/" ~ opt(database) ~ opt("?" ~ options)) ^^ {
      case _ ~ credentials ~ host ~ hosts ~ None =>
        MongoClientUri(
          credentials = credentials.map(_._1),
          hosts = hosts.map(_._2).toSet + host
        )

      case _ ~ credentials ~ host ~ hosts ~ Some(_ ~ database ~ options) =>
        MongoClientUri(
          credentials = credentials.map(_._1),
          hosts = hosts.map(_._2).toSet + host,
          database = database,
          options = options.map(_._2).getOrElse(Map.empty)
        )
    }
  }
} 
开发者ID:dgouyette,项目名称:tepkin,代码行数:62,代码来源:MongoClientUriParser.scala


示例7: LPLexer

//设置package包名称以及导入依赖的类
package parser

import scala.util.parsing.combinator.RegexParsers

object LPLexer extends RegexParsers {
  override def skipWhitespace: Boolean = true
  override val whiteSpace = "[ \t\r\f\n]+".r

  def apply(lp: String): Either[LPError, List[LPToken]] = {
    parse(tokens, lp) match {
      case NoSuccess(msg, next) => Left(LPLexerError(msg))
      case Success(result, next) => Right(result)
    }
  }

  def identifier: Parser[VAR]    = "[a-zA-Z_][a-zA-Z0-9_]*".r ^^ VAR
  def scalar:     Parser[SCALAR] = "[+|-][0-9]*".r ^^ (str => SCALAR(str.toInt))
  def max   = "max".r ^^ (_ => MAX)
  def min   = "min".r ^^ (_ => MIN)
  def st    = "st".r  ^^ (_ => ST)
  def plus  = "+".r ^^  (_ => PLUS)
  def minus = "-".r ^^  (_ => MINUS)
  def equal = "=".r ^^ (_ => EQ)
  def less  = "<".r ^^ (_ => LESS)
  def eoc   = "\n".r ^^ (_ => EOL)

  def tokens: Parser[List[LPToken]] =
    phrase(rep1(min | max | identifier | scalar | st | plus | minus | equal | eoc)) ^^ ???

} 
开发者ID:Schwenger,项目名称:ScalaSimplex,代码行数:31,代码来源:LPLexer.scala


示例8: Lexer

//设置package包名称以及导入依赖的类
package parsing.action

import scala.util.Try
import scala.util.matching.Regex
import scala.util.parsing.combinator.RegexParsers

object Lexer extends RegexParsers {

  override def skipWhitespace: Boolean = true
  override val whiteSpace: Regex = "[ \t\r\f]+".r

  def apply(input: String): Try[List[ActionParseToken]] = parse(tokens, input.toLowerCase) match {
    case NoSuccess(msg, next) => scala.util.Failure(ActionLexerError(msg))
    case Success(result, next) => scala.util.Success(result)
  }

  def number: Parser[NUMBER] = "[0-9]".r ^^ { s => NUMBER(s) }

  def surrender = "surrender|give up|forfeit".r ^^ (_ => SURRENDER)
  def east      = "east|right".r ^^ (_ => EAST)
  def south     = "south|down".r ^^ (_ => SOUTH)
  def placecmd  = "place|set".r  ^^ (_ => PLACECMD)
  def west      = "west|left".r  ^^ (_ => WEST)
  def north     = "north|up".r   ^^ (_ => NORTH)
  def my        = "my|the".r     ^^ (_ => MY)
  def position  = "position"     ^^ (_ => POSITION)
  def capstone  = "capstone"     ^^ (_ => CAPSTONE)
  def minion    = "minion"       ^^ (_ => MINION)
  def stack     = "stack"        ^^ (_ => STACK)
  def slidecmd  = "slide"        ^^ (_ => SLIDECMD)
  def wall      = "wall"         ^^ (_ => WALL)
  def movecmd   = "move"         ^^ (_ => MOVECMD)
  def drop      = "drop"         ^^ (_ => DROP)
  def from      = "from"         ^^ (_ => FROM)
  def at        = "at"           ^^ (_ => AT)
  def to        = "to"           ^^ (_ => TO)
  def a         = "a"            ^^ (_ => A)
  def lpar      = "("            ^^ (_ => LPAR)
  def rpar      = ")"            ^^ (_ => RPAR)
  def comma     = ","            ^^ (_ => COMMA)

  def tokens: Parser[List[ActionParseToken]] = {
    phrase(rep1(
      number | surrender | placecmd | movecmd | position | capstone | minion | north | south | wall | drop |
      from | west | east | at | to | lpar | rpar | comma | stack | slidecmd | my | a
    ))
  }

} 
开发者ID:Schwenger,项目名称:Tak,代码行数:50,代码来源:Lexer.scala


示例9: validName

//设置package包名称以及导入依赖的类
package com.criteo.dev.cluster.utils.ddl

import scala.util.parsing.combinator.RegexParsers

trait BaseParser extends RegexParsers {
  def validName: Parser[String] = "`".? ~> "[A-Za-z0-9_]+".r  <~ "`".?

  def hiveStringLiteral: Parser[String] = ("'" | "\"") ~> "[^'\"]*".r <~ ("'" | "\"")

  def properties(delimiter: String = "="): Parser[Map[String, String]] = "(" ~> repsep(hiveStringLiteral ~ delimiter ~ hiveStringLiteral, ",") <~ ")" ^^ {
    _.map { case k ~ _ ~ v =>
      (k, v)
    }.toMap
  }

  def comment: Parser[String] = "comment" ~> hiveStringLiteral

  def int: Parser[Int] = "\\d+".r ^^ (_.toInt)

  // parser for case insensitive string literal
  implicit def caseInsensitiveLiteral(s: String): Parser[String] = new Parser[String] {
    def apply(in: Input) = {
      val source = in.source
      val offset = in.offset
      val start = handleWhiteSpace(source, offset)
      var i = 0
      var j = start
      while (i < s.length && j < source.length && s.charAt(i).toLower == source.charAt(j).toLower) {
        i += 1
        j += 1
      }
      if (i == s.length)
        Success(source.subSequence(start, j).toString, in.drop(j - offset))
      else {
        val found = if (start == source.length()) "end of source" else "`" + source.charAt(start) + "'"
        Failure("`" + s + "' expected but " + found + " found", in.drop(start - offset))
      }
    }
  }
} 
开发者ID:criteo,项目名称:berilia,代码行数:41,代码来源:BaseParser.scala


示例10: stringPlusPString

//设置package包名称以及导入依赖的类
package com.avsystem.scex.parsing

import scala.util.parsing.combinator.RegexParsers


trait PositionTrackingParsers extends RegexParsers {

  implicit class stringPlusPString(str: String) {
    def ~+(pstr: PString): PString =
      if (str.nonEmpty)
        pstr match {
          case PString(result, offset, length, mods) =>
            PString(str + result, offset, length, Modification(offset, str.length) +: mods)
        }
      else pstr
  }

  class ParserWithPos(parser: Parser[String]) extends Parser[PString] {
    def apply(in: Input) = parser(in).map { str =>
      PString(str, in.offset, in.offset + str.length, Vector.empty)
    }
  }

  implicit class stringWithPos(pattern: String) {
    def p: Parser[PString] =
      new ParserWithPos(pattern)

    def rp: Parser[PString] =
      new ParserWithPos(pattern.r)
  }

  def join(pstrs: Traversable[PString]) =
    if (pstrs.nonEmpty) pstrs.reduce(_ + _) else PString("", 0, 0, Vector.empty)

  def withOffset[T](parser: Parser[T]): Parser[(T, Int)] = new Parser[(T, Int)] {
    override def apply(in: Input) =
      parser.apply(in).map(r => (r, in.offset))
  }

}

object PositionTrackingParsers extends PositionTrackingParsers 
开发者ID:AVSystem,项目名称:scex,代码行数:43,代码来源:PositionTrackingParsers.scala


示例11: ParserException

//设置package包名称以及导入依赖的类
package com.nakoradio.scalc.core.parser

import scala.util.parsing.combinator.RegexParsers
import scala.util.parsing.input.Reader

case class ParserException(message: String) extends Exception


class PatternParser extends RegexParsers {
  final val NUMBER_REGEXP = "[-+]?(\\d+(\\.\\d*)?|\\.\\d+)"

  def number: Parser[BigDecimal] = NUMBER_REGEXP.r ^^ {
    BigDecimal(_)
  }

  def multipliable: Parser[BigDecimal] = "(" ~> summedTerms <~ ")" | number

  def mul: Parser[BigDecimal] = multipliable ~ rep(("*" | "/") ~ multipliable) ^^ {
    case base ~ list => list.foldLeft(base) {
      case (z, "*" ~ n) => z * n
      case (z, "/" ~ n) => if (n != 0) { z / n } else {
        throw ParserException("Division by zero")
      }
    }
  }

  def term: Parser[BigDecimal] = mul | number

  def summedTerms: Parser[BigDecimal] = term ~ rep(("+" | "-") ~ term) ^^ {
    case base ~ list => list.foldLeft(base) {
      case (z, "+" ~ s) => z + s
      case (z, "-" ~ s) => z - s
    }
  }

  def expression: Parser[BigDecimal] = summedTerms

  def nicerError(input: String, message: String, next: Reader[Char]): String = {
    // Until proper error reporting from parser, lets make number parsing errors a bit user friendly
    val nice = message.replace(NUMBER_REGEXP, "number").replaceAll("string matching regex ", "")
    f"Parsing failed due to [$nice] on input [$input] at position [${next.pos.column}]"
  }
} 
开发者ID:Arch-vile,项目名称:sCalc,代码行数:44,代码来源:PatternParser.scala


示例12: PatternExpEvaluator

//设置package包名称以及导入依赖的类
package com.nakoradio.scalc.core.parser

import scala.util.parsing.combinator.RegexParsers
import scala.util.parsing.combinator.RegexParsers
import scala.util.parsing.input.Reader
import javax.inject._
import scala.BigDecimal

class PatternExpEvaluator extends ExpressionEvaluator {

  def apply(input: String): EvaluatorResult = {

    try {
      val cleanInput = sanitize(input)
      val parser = new PatternParser()
      parser.parseAll(parser.expression, cleanInput) match {
        case parser.Success(value, _)        => EvaluatorSuccess(value)
        case parser.NoSuccess(message, next) => EvaluatorFailure(parser.nicerError(cleanInput, message, next))
      }
    } catch {
      case ex: ParserException => EvaluatorFailure(ex.message)
      case e: Exception        => EvaluatorFailure("Unexpected error")
    }
  }

  // Remove extensive whitespace and sanitize some aspects not handled by grammar
  // TODO: These should be included in the grammar
  def sanitize(input: String): String = {
    input.replaceAll("\\s+", " ") // First strip consequent whitespace
      .replaceAll("""(\d)\s?\(""", "$1*(") //then add missing '*' between number and parenthesis
      .replaceAll("""\)\s?(\d)""", ")*$1") //then add missing '*' between parenthesis and number
      .replaceAll("""\)\s?\(""", ")*(") // then add missing '*' between parenthesis
      .replaceAll(""",""", ".") // Also accept ',' as decimal separator
  }

} 
开发者ID:Arch-vile,项目名称:sCalc,代码行数:37,代码来源:PatternExpEvaluator.scala


示例13: regexMatchedParser

//设置package包名称以及导入依赖的类
package com.github.kczulko.isc.dhcp.parsers

import scala.util.matching.Regex
import scala.util.matching.Regex.Match
import scala.util.parsing.combinator.RegexParsers

trait RegexMatchedParser extends RegexParsers {
  def regexMatchedParser(r: Regex): Parser[Match] = (in: Input) => {
    val source = in.source
    val offset = in.offset
    val start = handleWhiteSpace(source, offset)
    r findPrefixMatchOf source.subSequence(start, source.length) match {
      case Some(matched) =>
        Success(matched, in.drop(start + matched.end - offset))
      case None =>
        Failure(
          s"string matching regex `$r' expected but `${in.first}' found",
          in.drop(start - offset)
        )
    }
  }
} 
开发者ID:kczulko,项目名称:isc-dhcp-leases-parser,代码行数:23,代码来源:RegexMatchedParser.scala


示例14: Lexer

//设置package包名称以及导入依赖的类
package compiler.lexer

import compiler.{LexerError, Location}

import scala.util.parsing.combinator.RegexParsers

object Lexer extends RegexParsers {

  def identifier = positioned {
    """[A-Za-z\_][A-Za-z0-9\_]*""".r ^^ IDENTIFIER.compose(_.toLowerCase)
  }

  def number = positioned {
    "-?[0-9]+".r ^^ NUMBER.compose(_.toInt)
  }

  def booleanConst = positioned {
    """(?i)(true|false)""".r ^^ BOOLEAN_CONST.compose(_.toBoolean)
  }

  def string = positioned {
    """'[^']*'""".r ^^ STRING_LITERAL.compose(_.drop(1).dropRight(1))
  }

  def semicolon = positioned {";" ^^ (_ => SEMICOLON())}
  def colon = positioned {":" ^^ (_ => COLON())}
  def leftParenthesis = positioned {"(" ^^ (_ => LEFT_PARENTHESIS())}
  def rightParenthesis = positioned {")" ^^ (_ => RIGHT_PARENTHESIS())}
  def dot = positioned {"." ^^ (_ => DOT())}
  def assign = positioned {":=" ^^ (_ => ASSIGN())}
  def comma = positioned {"," ^^ (_ => COMMA())}
  def plus = positioned {"+" ^^ (_ => PLUS())}
  def minus = positioned {"-" ^^ (_ => MINUS())}
  def times = positioned {"*" ^^ (_ => TIMES())}
  def div = positioned {"/" ^^ (_ => DIVISION())}
  def modulo = positioned {"%" ^^ (_ => MODULO())}
  def less = positioned {"<" ^^ (_ => LESS())}
  def lessEquals = positioned {"<=" ^^ (_ => LESS_EQUALS())}
  def greater = positioned {">" ^^ (_ => GREATER())}
  def greaterEquals = positioned {">=" ^^ (_ => GREATER_EQUALS())}
  def notEquals = positioned {"<>" ^^ (_ => NOT_EQUALS())}
  def equals = positioned {"=" ^^ (_ => EQUALS())}


  def and = positioned {"(?i)and".r ^^ (_ => AND())}
  def or = positioned {"(?i)or".r ^^ (_ => OR())}


  def tokens: Parser[List[Token]] =
    phrase(rep1(number | notEquals | lessEquals | less | greaterEquals | greater | equals
      | plus | minus | times | div | modulo
      | assign | colon | comma | dot | leftParenthesis | rightParenthesis | semicolon
      | and | or | booleanConst | identifier | string))

  def apply(code: String): Either[List[LexerError], List[Token]] =
    parse(tokens, code) match {
      case Success(result, _) => Right(result)
      case NoSuccess(message, next) => Left(List(LexerError(Location(next.pos), message)))
    }
} 
开发者ID:darthorimar,项目名称:pascalJvm,代码行数:61,代码来源:Lexer.scala


示例15: shouldParse

//设置package包名称以及导入依赖的类
package es.weso.rdf.turtle.parser

import scala.util.parsing.combinator.RegexParsers
import org.scalatest.FunSpec
import org.scalatest.Matchers

trait TestParser
    extends FunSpec
    with RegexParsers
    with Matchers {

  def shouldParse(p: Parser[String], s: String) {
    shouldParseGeneric(p, s, s)
  }

  // Only checks if parser succeeds
  def shouldParseGen[A](p: Parser[A], s: String) {
    it("Should parse \"" + s + "\"") {
      val result = parseAll(p, s) match {
        case Success(x, _) => true
        case NoSuccess(msg, _) => fail(msg)
      }
    }
  }

  def shouldParseGeneric[A](p: Parser[A], s: String, a: A) {
    it("Should parse \"" + s + "\"" + " and return " + a.toString) {
      val result = parseAll(p, s) match {
        case Success(x, _) => x
        case NoSuccess(msg, _) => fail(msg)
      }
      result should be(a)
    }
  }

  def shouldNotParse[A](p: Parser[A], s: String) {
    it("Should not parse \"" + s + "\"") {
      val result = parseAll(p, s) match {
        case Success(x, _) => fail("Should not parse " + s + ", but parsed value " + x)
        case NoSuccess(msg, _) => info("It didn't parse as expected. Message: " + msg)
      }
    }
  }

  
  def shouldNotParseNamed[A](
    testName: String,
    p: Parser[A],
    s: String
  ) {
    it("Should not parse " + testName) {
      val result = parseAll(p, s) match {
        case Success(x, s1) =>
          fail("String: " + s + " should not parse, but it parsed with value: " + x + " and " + s1)
        case NoSuccess(msg, _) =>
          info("It didn't parse as expected. Message: " + msg)
      }
    }
  }

} 
开发者ID:labra,项目名称:turtleparser-with-combinators,代码行数:62,代码来源:TestParser.scala


示例16: Exercise01

//设置package包名称以及导入依赖的类
package forimpatient.chapter19

import scala.util.parsing.combinator.RegexParsers


object Exercise01 extends App {
  println("Chapter 19 Exercise 01")

  val parser = new ExprParser
  val result = parser.parseAll(parser.expr, "52 / 2 % 9 / 4 - 2 - 4")
  if (result.successful) println(result.get)


  class ExprParser extends RegexParsers {
    val number = "[0-9]+".r

    def expr: Parser[Int] = term ~ rep(("+" | "-") ~ term ^^ {
      case "+" ~ t => t
      case "-" ~ t => -t
    }) ^^ {case t ~ r => t + r.sum}

    def term: Parser[Int] = factor ~ rep(("*" | "/" | "%") ~ factor) ^^ {
      case f ~ r => r.foldLeft(f)((n, pair) => pair._1 match {
          case "*" => n * pair._2;
          case "/" => n / pair._2
          case "%" => n % pair._2
        })
    }

    def factor: Parser[Int] = number ^^ (_.toInt)| "(" ~> expr <~ ")"
  }
} 
开发者ID:Kiryna,项目名称:Scala-for-the-Impatient,代码行数:33,代码来源:Exercise01.scala


示例17: Exercise05

//设置package包名称以及导入依赖的类
package forimpatient.chapter19

import scala.util.parsing.combinator.RegexParsers
import scala.xml.{Attribute, MetaData, Node, NodeBuffer, NodeSeq, Null, Text, TopScope, UnprefixedAttribute, Elem => XmlElem}


object Exercise05 extends App {
  println("19 Exercise 05")

  val parser = new XmlParser
  val XML = "<html><head><title>Fred's Memoirs!</title></head>" +
    "<body><a href=\"http://scala-lang.org\">The <em>Scala</em> language?</a></body></html>"
  val result = parser.parseAll(parser.sequence, XML)
  if (result.successful) println(result.get)

  class XmlParser extends RegexParsers {
    val label = "[a-z]+".r
    val attr = """[a-z0-9 .:\/-]+""".r
    val text = """[a-zA-Z0-9 .:,!?'\/-]+""".r

    def sequence: Parser[NodeSeq] = rep(tag | empty) ^^ { r => (new NodeBuffer ++ r).filter(_ != null)}

    def tag: Parser[Node] = ("<" ~> label ~ attributes <~ ">") ~ sequence ~ textWithTags ~ ("</" ~> label <~ ">") ^^ {
      case tagOpen ~ attr ~ beginning ~ ending ~ tagClose if tagOpen == tagClose =>
        XmlElem(null, tagOpen, attr, TopScope, true, beginning ++ ending: _*)
      case _ => null
    }

    def empty: Parser[Node] = "<" ~> label <~ "/>" ^^ {
      t  => XmlElem(null, t, Null, TopScope, minimizeEmpty = true)
    }

    def textWithTags: Parser[NodeSeq] = rep(rowText ~ sequence) ^^ {
      r => {val buf = new NodeBuffer; for (el <- r) {buf += el._1; buf ++= el._2 }; buf}
    }

    def rowText: Parser[Node] = text ^^ {t => Text(t)}

    def attributes: Parser[MetaData] = rep(label ~ ("=\"" ~> attr <~"\"" | "=\'" ~> attr <~"\'" )) ^^ {
      a => a.foldRight(Null: MetaData)((pair, next) => Attribute(null, pair._1, pair._2, next))
    }
  }
} 
开发者ID:Kiryna,项目名称:Scala-for-the-Impatient,代码行数:44,代码来源:Exercise05.scala


示例18: Version

//设置package包名称以及导入依赖的类
package com.tapad.docker

import scala.util.parsing.combinator.RegexParsers

case class Version(major: Int, minor: Int, release: Int)

object Version extends RegexParsers {
  def apply(version: String): Version = {
    parseVersion(version)
  }

  def parseVersion(version: String): Version = {
    parse(parser, version) match {
      case Success(ver, _) => ver
      case NoSuccess(msg, _) => throw new RuntimeException(s"Could not parse Version from $version: $msg")
    }
  }

  private val positiveWholeNumber: Parser[Int] = {
    ("0".r | """[1-9]?\d*""".r).map(_.toInt).withFailureMessage("non-negative integer value expected")
  }

  private val parser: Parser[Version] = {
    positiveWholeNumber ~ ("." ~> positiveWholeNumber) ~ ("." ~> positiveWholeNumber) ^^ {
      case major ~ minor ~ release => Version(major, minor, release)
    }
  }
} 
开发者ID:Tapad,项目名称:sbt-docker-compose,代码行数:29,代码来源:Version.scala



注:本文中的scala.util.parsing.combinator.RegexParsers类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Scala any类代码示例发布时间:2022-05-23
下一篇:
Scala HttpServletRequest类代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap