本文整理汇总了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)
}
}
}