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


Scala PatternSyntaxException类代码示例

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


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

示例1: RegexSelector

//设置package包名称以及导入依赖的类
package haishu.crawler.selector

import java.util.regex.{Pattern, PatternSyntaxException}

import org.apache.commons.lang3.StringUtils

class RegexSelector(pattern: Pattern, group: Int = 1) extends Selector {

  override def select(text: String): String = selectGroup(text).get(group)

  override def selectSeq(text: String): Seq[String] = {
    selectGroupSeq(text).map(_.get(group))
  }

  def selectGroup(text: String): RegexResult = {
    val matcher = pattern.matcher(text)
    if (matcher.find()) {
      val groups = Array.tabulate(matcher.groupCount() + 1)(matcher.group)
      RegexResult(groups)
    } else RegexResult.empty
  }

  def selectGroupSeq(text: String): Seq[RegexResult] = {
    val matcher = pattern.matcher(text)
    var resultSeq: Seq[RegexResult] = Vector()
    while (matcher.find()) {
      val groups = Array.tabulate(matcher.groupCount() + 1)(matcher.group)
      resultSeq :+= RegexResult(groups)
    }
    resultSeq
  }
}

object RegexSelector {

  def apply(expr: String, group: Int): RegexSelector = new RegexSelector(compileRegex(expr), group)

  def apply(expr: String): RegexSelector = {
    val p = compileRegex(expr)
    val group = if (p.matcher("").groupCount() == 0) 0 else 1
    new RegexSelector(p, group)
  }

  private def compileRegex(expr: String): Pattern = {
    if (StringUtils.isBlank(expr)) throw new IllegalArgumentException("regex must not be empty")

    try {
      Pattern.compile(expr, Pattern.DOTALL | Pattern.CASE_INSENSITIVE)
    } catch {
      case e: PatternSyntaxException =>
        throw new IllegalArgumentException("invalid regex " + expr, e)
    }
  }

} 
开发者ID:hualongdata,项目名称:hl-crawler,代码行数:56,代码来源:RegexSelector.scala


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