当前位置: 首页>>代码示例>>Scala>>正文


Scala Regex类代码示例

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


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


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