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

Scala Regex类代码示例

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

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



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

示例1: XML

//设置package包名称以及导入依赖的类
package org.cg.scala.dhc.util

import java.io.{ByteArrayOutputStream, File, FileInputStream}

import scala.util.matching.Regex
import scala.xml.Elem
import scala.xml.factory.XMLLoader
import javax.xml.parsers.SAXParser

object XML extends XMLLoader[Elem] {
  override def parser: SAXParser = {
    val f = javax.xml.parsers.SAXParserFactory.newInstance()
    f.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
    f.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    f.newSAXParser()
  }
}

object FileUtil {

  def recursiveListFileInfos(baseDir: String, regex: String): Array[FileInfo] =
    recursiveListFiles(baseDir, regex).map(f => new FileInfo(f.getName, f.getCanonicalPath, f.lastModified()))

  def recursiveListFiles(baseDir: String, regex: String): Array[File] = recursiveListFiles(new File(baseDir), new Regex(regex))

  def recursiveListFiles(f: File, r: Regex): Array[File] = {
    val these = f.listFiles
    if (these != null) {
      val good = these.filter(f => r.findFirstIn(f.getName).isDefined)
      good ++ these.filter(_.isDirectory).flatMap(recursiveListFiles(_, r))
    }
    else
      new Array[File](0)
  }

  def fileToString(file: File) = {
    val inStream = new FileInputStream(file)
    val outStream = new ByteArrayOutputStream
    try {
      var reading = true
      while (reading) {
        inStream.read() match {
          case -1 => reading = false
          case c => outStream.write(c)
        }
      }
      outStream.flush()
    }
    finally {
      inStream.close()
    }
    new String(outStream.toByteArray())
  }

} 
开发者ID:curiosag,项目名称:datahubchecker,代码行数:56,代码来源:FileUtil.scala


示例2: InAppropriateLanguage

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

import scala.util.matching.Regex



  object InAppropriateLanguage {
    val words : List[Regex] = List(
      "fuck".r,
      "bastard".r,
      "dick".r,
      "vagina".r,
      "twat".r,
      "kill".r
    )
  } 
开发者ID:ZDevelop94,项目名称:ZolvedIT,代码行数:17,代码来源:InAppropriateLanguage.scala


示例3: RandomVal

//设置package包名称以及导入依赖的类
package com.jetprobe.fastgen.generators.entity

import java.security.SecureRandom

import com.jetprobe.fastgen.generators.{
  EntityGenerator,
  FieldOption,
  StringType
}
import com.typesafe.config.Config

import scala.util.matching.Regex


class RandomVal(datasetConfig: Config, regexMatcher: Regex.MatchIterator)
    extends EntityGenerator(datasetConfig, regexMatcher)

object RandomVal {
  val abc = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
  val numberStr = "0123456789"
  lazy val rnd = new SecureRandom()

  def apply(datasetConfig: Config,
            regexMatcher: Regex.MatchIterator): RandomVal = {
    val random = new RandomVal(datasetConfig, regexMatcher)

    random.addField("Random.String", StringType, (fieldOpt: FieldOption) => {
      val sb = new StringBuilder(10)
      for (i <- 0 until 20) {
        sb.append(abc(rnd.nextInt(abc.length)))
      }
      sb.toString
    })

    random.addField(
      "Random.number",
      StringType,
      (fieldOpt: FieldOption) => {
        val sb = new StringBuilder(10)
        for (i <- 0 until 10) {
          sb.append(abc(rnd.nextInt(numberStr.length)))
        }
        sb.toString
      }
    )

    random
  }
} 
开发者ID:amezng,项目名称:fastgen,代码行数:50,代码来源:RandomVal.scala


示例4: PersonGen

//设置package包名称以及导入依赖的类
package com.jetprobe.fastgen.generators.entity

import com.jetprobe.fastgen.generators._
import com.typesafe.config.Config

import scala.util.matching.Regex


class PersonGen(datasetConfig: Config, regexMatcher: Regex.MatchIterator)
    extends EntityGenerator(datasetConfig, regexMatcher)

object PersonGen {
  import scala.util.Random
  def apply(datasetConfig: Config,
            regexMatcher: Regex.MatchIterator): PersonGen = {
    val person = new PersonGen(datasetConfig, regexMatcher)

    // firstName
    person.addField("Person.firstName", StringType, (fieldOpt: FieldOption) => {
      val arr = person.dataset.get(fieldOpt.getName).get
      Generator.getRNG(arr.length, arr)
    })

    //lastName
    person.addField("Person.lastName", StringType, (fieldOpt: FieldOption) => {
      val arr = person.dataset.get(fieldOpt.getName).get
      Generator.getRNG(arr.length, arr)
    })

    //Support for parsing and generating age
    person.addField(
      "Person.age",
      IntType,
      (fieldOpt: FieldOption) => {
        val randomInt = fieldOpt match {
          case opt: IntOption =>
            opt.minVal + Random.nextInt((opt.maxVal - opt.minVal) + 1)
          case _ => Random.nextInt(100)
        }
        randomInt.toString
      }
    )

    person

  }

} 
开发者ID:amezng,项目名称:fastgen,代码行数:49,代码来源:PersonGen.scala


示例5: Lv19

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

import scala.util.matching.Regex


object Lv19 extends App {

  val requested = "CRnCaCaCaSiRnBPTiMgArSiRnSiRnMgArSiRnCaFArTiTiBSiThFYCaFArCaCaSiThCaPBSiThSiThCaCaPTiRnPBSiThRnFArArCaCaSiThCaSiThSiRnMgArCaPTiBPRnFArSiThCaSiRnFArBCaSiRnCaPRnFArPMgYCaFArCaPTiTiTiBPBSiThCaPTiBPBSiRnFArBPBSiRnCaFArBPRnSiRnFArRnSiRnBFArCaFArCaCaCaSiThSiThCaCaPBPTiTiRnFArCaPTiBSiAlArPBCaCaCaCaCaSiRnMgArCaSiThFArThCaSiThCaSiRnCaFYCaSiRnFYFArFArCaSiRnFYFArCaSiRnBPMgArSiThPRnFArCaSiRnFArTiRnSiRnFYFArCaSiRnBFArCaSiRnTiMgArSiThCaSiThCaFArPRnFArSiRnFArTiTiTiTiBCaCaSiRnCaCaFYFArSiThCaPTiBPTiBCaSiThSiRnMgArCaF"
  val transitions = List(("Al", "ThF"), ("Al", "ThRnFAr"), ("B", "BCa"), ("B", "TiB"), ("B", "TiRnFAr"), ("Ca", "CaCa"), ("Ca", "PB"), ("Ca", "PRnFAr"), ("Ca", "SiRnFYFAr"), ("Ca", "SiRnMgAr"), ("Ca", "SiTh"), ("F", "CaF"), ("F", "PMg"), ("F", "SiAl"), ("H", "CRnAlAr"), ("H", "CRnFYFYFAr"), ("H", "CRnFYMgAr"), ("H", "CRnMgYFAr"), ("H", "HCa"), ("H", "NRnFYFAr"), ("H", "NRnMgAr"), ("H", "NTh"), ("H", "OB"), ("H", "ORnFAr"), ("Mg", "BF"), ("Mg", "TiMg"), ("N", "CRnFAr"), ("N", "HSi"), ("O", "CRnFYFAr"), ("O", "CRnMgAr"), ("O", "HP"), ("O", "NRnFAr"), ("O", "OTi"), ("P", "CaP"), ("P", "PTi"), ("P", "SiRnFAr"), ("Si", "CaSi"), ("Th", "ThCa"), ("Ti", "BP"), ("Ti", "TiTi"), ("e", "HF"), ("e", "NAl"), ("e", "OMg"))
      .sortBy(-_._2.length)

  val combs = (for (trans <- transitions) yield getCombs(requested, trans, List())).flatten.filter(!_.isEmpty).distinct

  def getCombs(stringa: String, repl: (String, String), acc: List[String]): List[String] = {
    val chars = stringa.split("(?<=" + repl._1 + ")").toList
    (for (i <- chars.indices) yield if (chars(i).contains(repl._1))
      chars.patch(i, Seq(chars(i).replace(repl._1, repl._2)), 1) mkString ""
    else "").toList
  }

  def getSubs(xs: String, i: Int = 0) : Int = {
    transitions.find { case (k,v) => xs contains k } map {
      case (k,v) =>
        val mtc = new Regex(k).findFirstMatchIn(xs).get
        mtc.before + v + mtc.after
    } match {
      case Some(n) => getSubs(n, i+1)
      case None => i
    }
  }

  println("SOLUTION 1: " + combs.length)
  println("SOLUTION 2: " + getSubs(requested))
} 
开发者ID:simonecottini,项目名称:adventofcode-scala-2015,代码行数:35,代码来源:Lv19.scala


示例6: TaggedCorpus

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

import scala.io.Source
import scala.util.matching.Regex
import scala.collection.mutable.HashSet


abstract class TaggedCorpus {
  val posSymbSet: HashSet[String]
  def getSentIter: TaggedSentIter
}

abstract class PatternCorpus extends TaggedCorpus {
  val filename: String
  val pattern: Regex

  // TODO: wrap in try/catch block or figure out how to deal with `source`
  def getSentIter: TaggedSentIter = {
    val source = Source.fromInputStream(getClass.getResourceAsStream(filename))
    for (line <- source.reset().getLines() if line.trim.nonEmpty)
      yield pattern.findAllMatchIn(line).map( m => TagTuple(m.group("word"),m.group("symb")) )
  }
}

case class GeneCorpus(filename: String) extends PatternCorpus {
  val pattern = new Regex("""([^\s\|]+)\|([^\s\|]+)""", "word", "symb")
  val posSymbSet = HashSet("I-GENE")
}

case class WikiCorpus(filename: String) extends PatternCorpus {
  val pattern = new Regex("""([^\s\|]+)\|([^\|]+)\|([^\s\|]+)""", "word", "POS", "symb")
  val posSymbSet = HashSet("I-MISC","I-PER","I-ORG","I-LOC")
} 
开发者ID:MChamberlin,项目名称:NERtagger,代码行数:34,代码来源:Corpus.scala


示例7: Encryption

//设置package包名称以及导入依赖的类
import scala.annotation.tailrec
import scala.collection.mutable
import scala.util.Random
import scala.util.matching.Regex


object Encryption {
  lazy val runLengthEncoding: Regex = """(\d+)(".*?")""".r

  def frequencyMap(data: String): Map[Char, Int] = {
    var uniqueItems = mutable.HashMap[Char, Int]()
    for (character <- data) {
      if(uniqueItems.contains(character)){
        uniqueItems(character) = uniqueItems(character) + 1
      }
      else {
        uniqueItems += (character -> 0)
      }
    }
    uniqueItems.toMap
  }

  def substituent(seed: Long = System.nanoTime()): IndexedSeq[Char] =
    new Random(seed).shuffle((Char.MinValue to Char.MaxValue).filter(Character.isISOControl _))

  def runLengthEncode(data: String): String = {
    @tailrec
    def encode(input: String, accumulator: Seq[(Char, Int)]): Seq[(Char, Int)] =
      if (!input.isEmpty) accumulator
      else {
        val groupLength = input.takeWhile(x => x == input.head).length
        encode(input.drop(groupLength), (input.head, groupLength) +: accumulator)
      }

    encode(data, Seq()).map(item => s"""${item._2}"${item._1}"""").mkString("")
  }

  def runLengthDecode(data: String): String =
    runLengthEncoding.findAllMatchIn(data).map(matched => matched.group(1) * matched.group(0).toInt).mkString("")
} 
开发者ID:tamchow,项目名称:ScalaStuff,代码行数:41,代码来源:Encryption.scala


示例8: PathOps

//设置package包名称以及导入依赖的类
package com.github.stonexx.scala.util

import java.nio.file.Files
import java.nio.file.Path

import org.apache.commons.io.FilenameUtils.{getBaseName, getExtension}
import org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric

import scala.util.matching.Regex
import scala.util.matching.Regex.Groups

object PathOps {
  final val RegexNumberedBaseName: Regex = """(.*)\((\d+)\)$""".r
}

final class PathOps(val self: Path) extends AnyVal {
  import PathOps._

  def nonComflictPath: Path = {
    var path = if (Files.isDirectory(self)) self.resolve(randomAlphanumeric(8)) else self
    if (Files.exists(path)) {
      val (basename, beginCount, suffix) = {
        val filename = path.getFileName.toString
        val (maybeNumberedBasename, suffix) = Option(getBaseName(filename)).filter(_.nonEmpty) match {
          case Some(name) => name -> Option(getExtension(filename)).filter(_.nonEmpty).map("." + _).getOrElse("")
          case None => filename -> ""
        }
        RegexNumberedBaseName.findFirstMatchIn(maybeNumberedBasename) match {
          case Some(Groups(name, cnt)) => (name, cnt.toInt, suffix)
          case None => (maybeNumberedBasename, 1, suffix)
        }
      }
      var count = beginCount
      do {
        path = path.resolveSibling(s"$basename($count)$suffix")
        count += 1
      } while (Files.exists(path))
    }
    path
  }
}

trait ToPathOps {
  implicit def toPathOps(x: Path): PathOps = new PathOps(x)
} 
开发者ID:stonexx,项目名称:utils,代码行数:46,代码来源:PathOps.scala


示例9: message

//设置package包名称以及导入依赖的类
package com.pygmalios.reactiveinflux.error

import scala.util.matching.Regex

sealed trait ReactiveInfluxError {
  def message: String
}

object ReactiveInfluxError {
  val patterns: Map[Regex, (String) => ReactiveInfluxError] = Map(
    "database already exists".r -> DatabaseAlreadyExists.apply,
    "database not found:.*".r -> DatabaseNotFound.apply,
    "(?s)partial write:.*".r -> PartialWrite.apply
  )

  def apply(message: String): ReactiveInfluxError = {
    patterns.collectFirst {
      case (regex, factory) if regex.unapplySeq(message).isDefined => factory(message)
    }.getOrElse(OtherErrorType(message))
  }

}

case class DatabaseAlreadyExists(message: String) extends ReactiveInfluxError
case class DatabaseNotFound(message: String) extends ReactiveInfluxError
case class PartialWrite(message: String) extends ReactiveInfluxError
case class OtherErrorType(message: String) extends ReactiveInfluxError 
开发者ID:pygmalios,项目名称:reactiveinflux,代码行数:28,代码来源:ReactiveinfluxErrorType.scala


示例10: ItalianVATIdNumberFinder

//设置package包名称以及导入依赖的类
package org.pdfextractor.algorithm.finder.it

import java.util.Locale

import org.pdfextractor.algorithm.candidate.Candidate
import org.pdfextractor.algorithm.finder.AbstractFinder
import org.pdfextractor.algorithm.finder.it.ItalianRegexPatterns._
import org.pdfextractor.algorithm.parser.{ParseResult, Phrase}
import org.pdfextractor.db.domain.dictionary.PaymentFieldType.VATIN
import org.pdfextractor.db.domain.dictionary.{PaymentFieldType, SupportedLocales}
import org.springframework.stereotype.Service

import scala.collection.mutable
import scala.util.matching.Regex

@Service
class ItalianVATIdNumberFinder
  extends AbstractFinder(SupportedLocales.ITALY, VATIN, ItVatinR, ItVatinValueR, true, true) {

 override def searchValuesFromPhrase(
                                       phrase: Phrase,
                                       parseResult: ParseResult,
                                       valuePattern2: Regex): mutable.Buffer[Candidate] = {
    searchPattern.get
      .findAllIn(parseResult.text)
      .map(getValuePattern.findAllIn(_))
      .filter(isValueAllowed(_))
      .map(buildCandidate1(_))
      .toBuffer
  }

  override def isValueAllowed(value: Any): Boolean = {
    Option(value).isDefined &&
      value.isInstanceOf[String] &&
      value.asInstanceOf[String].length == 11 &&
      value.asInstanceOf[String].matches("""\d*""")
  }

  override def parseValue(raw: String): Any = raw

} 
开发者ID:kveskimae,项目名称:pdfalg,代码行数:42,代码来源:ItalianVATIdNumberFinder.scala


示例11: ExtractorExample

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

import scala.util.matching.Regex

object ExtractorExample {
  def main(args: Array[String]): Unit = {
    "[email protected]" match {
      case Email(user, domain) => println(user + "@" + domain)

    }
    "user1domain.com" match {
      case Email(user, domain) => println(user + "@" + domain)
      case _=> println("none")
    }
  }
}

object Email {
  def unapply(str: String) = new Regex("""(.*)@(.*)""")
    .unapplySeq(str) match {
      case Some(list) => Some(list(0), list(1))
      case _ => None
    }
} 
开发者ID:Chehao,项目名称:Akkala,代码行数:25,代码来源:ExtractorExample.scala


示例12: ScapsQuickAssist

//设置package包名称以及导入依赖的类
package scaps.eclipse.ui.view.quickfix

import scala.util.matching.Regex

import org.scalaide.core.quickassist.BasicCompletionProposal
import org.scalaide.core.quickassist.InvocationContext
import org.scalaide.core.quickassist.QuickAssist

class ScapsQuickAssist extends QuickAssist {

  val ValueNotFoundError: Regex = "not found: value (.*)".r

  override def compute(ctx: InvocationContext): Seq[BasicCompletionProposal] = {
    ctx.problemLocations.flatMap { location =>
      val possibleMatch = location.annotation.getText match {
        case ValueNotFoundError(member) =>
          List(ScapsQuickAssistProposal(member, ctx.icu, location.offset, location.length))
        case _ =>
          List.empty
      }
      //      possibleMatch.filter(_.isApplicable)
      possibleMatch
    }
  }
} 
开发者ID:scala-search,项目名称:scala-ide-scaps,代码行数:26,代码来源:ScapsQuickAssist.scala


示例13: Tokenizer

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

import scala.util.matching.Regex

abstract class Tokenizer {
  def apply(doc: String): List[String]
}

object Tokenizer {

  def pattern(tokenPattern: Regex): Tokenizer = {
    new Tokenizer {
      def apply(doc: String): List[String] = {
        tokenPattern.findAllIn(doc).toList
      }
    }
  }
} 
开发者ID:ngthanhtrung,项目名称:hisk,代码行数:19,代码来源:Tokenizer.scala


示例14: Comments

//设置package包名称以及导入依赖的类
package net.flatmap.cobra

import scala.util.matching.Regex

object Comments {
  def line(start: String) = new Regex(s"^\\s*$start\\s*(begin|end)\\s*\\#(\\w[\\w\\d-_]*)\\s*$$")
  def block(start: String, end: String) = new Regex(s"^\\s*$start\\s*(begin|end)\\s*\\#(\\w[\\w\\d-_]*)\\s*$end\\s*$$")
}

sealed abstract class Mode(val name: String, val mime: String, val regex: Regex, val alternatives: Regex, val fileendings: Set[String])
case object Scala extends Mode(
  "scala","text/x-scala",
  Comments.line("\\/\\/\\/+"),
  new Regex("(?s)\\/\\*\\(\\*\\/(.*?)\\/\\*\\)\\*\\/|\\/\\*\\(\\*\\/(.*?)\\/\\*\\|(.*?)\\)\\*\\/|\\/\\*\\((.*?)\\|\\*\\/(.*?)\\/\\*\\)\\*\\/"),
  Set("scala"))
case object Haskell extends Mode(
  "haskell","text/x-haskell",
  Comments.line("---+"),
  new Regex("(?s)\\{-\\(-\\}(.*?)\\{-\\)-\\}|\\{-\\(-\\}(.*?)\\{-\\|(.*?)\\)-\\}|\\{-\\((.*?)\\|-\\}(.*?)\\{-\\)-\\}"),
  Set("hs"))
case object Isabelle extends Mode(
  "isabelle","text/x-isabelle",
  Comments.block("\\(\\*\\*+","\\*\\)"),
  new Regex("(?s)\\(\\*\\(\\*\\)(.*?)\\(\\*\\)\\*\\)|\\(\\*\\(\\*\\)(.*?)\\(\\*\\|(.*?)\\)\\*\\)|\\(\\*\\((.*?)\\|\\*\\)(.*?)\\(\\*\\)\\*\\)"),
  Set("thy"))
case object Plain extends Mode("plain","text/plain",new Regex("$^"),new Regex("$^"),Set.empty)

object Mode {
  def modes = Set(Scala,Haskell,Isabelle)
} 
开发者ID:flatmap,项目名称:cobra,代码行数:31,代码来源:Modes.scala


示例15: StringOperations

//设置package包名称以及导入依赖的类
package io.clouderite.commons.scala.berries.string

import io.clouderite.commons.scala.berries.string.StringOperations.toStringOperations

import scala.util.matching.Regex
import scala.util.{Failure, Success, Try}
import scalaz.syntax.std.boolean._

class StringOperations(value: String) {
  def sliceLines(from: Int, to: Int): String = {
    require(from >= 0, "from parameter must be greater than or equal 0")
    require(to >= 0, "to parameter must be greater than or equal 0")
    require(from <= to, "from parameter must be lower than or equal to parameter")

    value.dropLines(from).takeLines(to - from + 1)
  }

  def negSliceLines(from: Int, to: Int): List[String] = {
    require(from >= 0, "from parameter must be greater than or equal 0")
    require(to >= 0, "to parameter must be greater than or equal 0")
    require(from <= to, "from parameter must be lower than or equal to parameter")
    
    List(value.takeLines(from), value.dropLines(to + 1))
  }

  def takeLines(num: Int): String = {
    require(num >= 0, "num parameter must be greater than or equal 0")
    value.linesWithSeparators.take(num).mkString
  }

  def dropLines(num: Int): String = {
    require(num >= 0, "num parameter must be greater than or equal 0")
    value.linesWithSeparators.drop(num).mkString
  }

  def matches(pattern: Regex): Boolean =
    pattern unapplySeq value isDefined

  def tryMatch(pattern: Regex): Try[String] =
    matches(pattern)
      .option(Success(value))
      .getOrElse(Failure(new IllegalArgumentException(s"cannot match value against pattern '$pattern'")))
}

object StringOperations {
  implicit def toStringOperations(value: String): StringOperations = new StringOperations(value)
} 
开发者ID:clouderite,项目名称:scala-berries,代码行数:48,代码来源:StringOperations.scala


示例16: PredicateRegEx

//设置package包名称以及导入依赖的类
package hmda.validation.dsl

import scala.util.matching.Regex

object PredicateRegEx {
  def validCensusTractFormat: Predicate[String] = stringMatching("^\\d{4}\\.\\d{2}$".r)

  def validEmail: Predicate[String] =
    stringMatching("^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$".r)

  def validPhoneNumber: Predicate[String] = stringMatching("^\\d{3}-\\d{3}-\\d{4}$".r)

  def validZipCode: Predicate[String] = stringMatching("^\\d{5}(?:-\\d{4})?$".r)

  def validTaxId: Predicate[String] = stringMatching("^\\d{2}-\\d{7}$".r)

  def numericMatching(pattern: String): Predicate[String] = stringMatching(regExFor(pattern))

  private def regExFor(pattern: String): Regex = {
    val result = pattern.map {
      case 'N' => "\\d"
      case '.' => "\\."
    }
    result.mkString("^", "", "$").r
  }

  private def stringMatching(regEx: Regex): Predicate[String] = {
    regEx.findFirstIn(_: String) match {
      case Some(_) => true
      case None => false
    }
  }
} 
开发者ID:cfpb,项目名称:hmda-platform,代码行数:34,代码来源:PredicateRegEx.scala


示例17: keyFor

//设置package包名称以及导入依赖的类
package com.innoave.soda.l10n

import scala.reflect.NameTransformer._
import scala.util.matching.Regex


trait KeyNamingStrategy {

  def keyFor(id: Int, name: String): String

}

object KeyNamingStrategy {

  def simpleTypeName(clazz: Class[_]): String =
    ((clazz.getName stripSuffix MODULE_SUFFIX_STRING split '.').last split
      Regex.quote(NAME_JOIN_STRING)).last

}

object NamesAsKeys extends KeyNamingStrategy {

  override def keyFor(id: Int, name: String): String = {
    if (name.isEmpty()) {
      throw new IllegalArgumentException("Name must not be empty")
    }
    name
  }

}

class CharacterSeparatedKeyNames(val separatorChar: Char) extends KeyNamingStrategy {

  override def keyFor(id: Int, name: String): String = {
    if (name.isEmpty()) {
      throw new IllegalArgumentException("Name must not be empty")
    }
    val result = new StringBuilder
    name.foldLeft((true, result)) { (r, c) =>
      if (c == '_')
        (true, r._2 + separatorChar)
      else
        if (c.isUpper)
          if (!r._1)
            (true, r._2 + separatorChar + c.toLower)
          else
            (true, r._2 + c.toLower)
        else
          (false, r._2 + c)
    }
    result.toString
  }

}

object DotSeparatedKeyNames extends CharacterSeparatedKeyNames('.') 
开发者ID:innoave,项目名称:soda,代码行数:57,代码来源:KeyNamingStrategy.scala


示例18: ReportWithIndex

//设置package包名称以及导入依赖的类
package com.xantoria.auditorium.reporting

import scala.util.matching.Regex


  lazy val configErrors: List[String] = {
    val checks: List[(Boolean, String)] = List(
      (
        timestamp match {
          case Report.timestampPattern() => true
          case _ => false
        },
        "Bad timestamp pattern"
      ),
      // TODO: Make this one of a configurable list of options (typesafe config)
      List("CREATE", "DELETE", "EDIT", "OTHER").contains(eventType) -> "Unsupported event type",
      (id.length <= Report.maxFieldLength) -> "Bad length: `id`",
      (objectId.length <= Report.maxFieldLength) -> "Bad length: `object_id`",
      (summary.length <= Report.maxFieldLength) -> "Bad length: `summary`",
      (user.map { _.length <= Report.maxFieldLength } getOrElse true) -> "Bad length: `user`"
    )

    checks flatMap {
      case (passed: Boolean, errorMsg: String) => if (passed) None else Some(errorMsg)
    }
  }
}

case class ReportWithIndex(r: Report, index: String) {
  override def toString: String = s"Report ${r.id} on index $index"
}

object Report {
  val timestampPattern: Regex = """^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z$""".r
  val maxFieldLength: Int = 512 // Fairly generous general limit, mostly to allow long summaries
} 
开发者ID:giftig,项目名称:auditorium,代码行数:37,代码来源:Report.scala


示例19: children

//设置package包名称以及导入依赖的类
package io.github.binaryfoo.ciscoconf

import scala.util.matching.Regex

trait ConfParent {
  def children: Seq[ConfLine]
  def findChildren(r: Regex): Seq[ConfLine] = {
    for (child <- children if r.findFirstIn(child.text).nonEmpty) yield child
  }
}

case class Config(children: Seq[ConfLine]) extends ConfParent

case class ConfLine(text: String, children: Seq[ConfLine] = Seq.empty) extends ConfParent {

  def get(name: String): Option[String] = {
    if (text.startsWith(name + " ")) {
      Some(text.replace(name + " ", ""))
    } else {
      children.collectFirst { case child if child.has(name) => child.get(name).get }
    }
  }

  def has(name: String): Boolean = get(name).nonEmpty
} 
开发者ID:binaryfoo,项目名称:cisco-conf-parser,代码行数:26,代码来源:ConfLine.scala


示例20: ParData

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

import com.lyrx.text.TextTypes._
import com.lyrx.text.bib.BibItem

import scala.util.matching.Regex





case class ParData[S](paragraphs: Pars,
                      outputFile: String,
                      replacements: Replacements[S] = Map[String, S](),
                      decorations:Replacements[S] = Map[String, S](),
                      footNotes: Seq[FootNote] = Nil,
                      sections: Seq[String] = Nil,
                      subSections: Seq[String] = Nil,
                      bibItems: Seq[BibItem] = Nil,
                      regexReplacers: RegexReplacers[S] =  Map[Regex,Replacer[S]]()
                     ) {

  def withReplacer(replacement: (Regex,Replacer[S]))={
    this.copy(regexReplacers= (this.regexReplacers + replacement))
  }

  def withFootNote(aTxt: Option[String]): ParData[S] =
    this.copy(footNotes = this.footNotes :+ FootNote(aTxt))
  def withBibItem(bibItem: BibItem) =
    this.copy(bibItems = bibItem +: this.bibItems)

  def section(): String = sections.head
  def subSection(): String = subSections.head
  def dropSection(): ParData[S] = this.copy(sections = this.sections.tail)
  def dropSubSection(): ParData[S] =
    this.copy(subSections = this.subSections.tail)

} 
开发者ID:lyrx,项目名称:lyrxgenerator,代码行数:39,代码来源:ParData.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Scala FileOutputStream类代码示例发布时间:2022-05-23
下一篇:
Scala URI类代码示例发布时间: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