加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

如何在scala中为两个或多个正则表达式使用模式匹配

发布时间:2020-12-16 10:03:02 所属栏目:安全 来源:网络整理
导读:我不明白如何使用模式匹配两个或更多正则表达式.例如,我写了以下程序: import scala.io.Source.{fromInputStream}import java.io._import java.net._object craw{ def main(args: Array[String]) { val url=new URL("http://contentexplore.com/iphone-6-am
我不明白如何使用模式匹配两个或更多正则表达式.例如,我写了以下程序:

import scala.io.Source.{fromInputStream}
import java.io._
import java.net._
object craw
{
  def main(args: Array[String])
  {
    val url=new URL("http://contentexplore.com/iphone-6-amazing-looks/")
    val content=fromInputStream(url.openStream).getLines.mkString("n")
    val x="<a href=("[^"]*")[^<]".r.
      findAllIn(content).
      toList.
      map(x=>x.substring(16,x.length()-2)).
      mkString("").
      split("/").
      mkString("").
      split(".com").
      mkString("").
      split("www.").
      mkString("").
      split(".html").
      toList
    print(x)
  }
}

以上读取所有锚标签.

import scala.io.Source.{fromInputStream}
import java.io._
import java.net._
object new1
{
  def main(args: Array[String])
  {
    val url=new URL("http://contentexplore.com/iphone-6-amazing-looks/")
    val content=fromInputStream(url.openStream).getLines.mkString("n")
    val x="<p>.*?</p>".r.
      findAllIn(content).
      toList.
      map(x=>x.substring(3,x.length()-4)).
      mkString("").
      split("</strong>").
      mkString("").
      split("</em>").
      mkString("").
      split(";").
      mkString("").
      split("<em>").
      mkString("").
      split("<strong>").
      mkString("").
      split("&nbsp").
      toList
    print(x)
  }
}

以上内容读入所有段落标签.

我想使用模式匹配将这两个正则表达式组合到一个程序中.可以指导我如何使用两个以上的正则表达式?

注意此问题与组合正则表达式有关,而与如何有效地解析HTML有关.

解决方法

如评论中所述,不建议使用正则表达式来解析HTML文件(或任何其他技术,除非您确定不能/不想使用某些现有文件,如jsoup).

出于教育目的,这里有一种通过模式匹配(使用正则表达式作为提取器)链接正则表达式的方法:

val LinkPattern = "<a href=("[^"]*")[^<]".r
val ParagraphPattern = "<p>.*?</p>".r
xmlNodeString match {
   case LinkPattern(c) => //c bound to capture group here
   case ParagraphPattern(d) => //d bound to capture group here
   case _ =>
}

注意:这假设您要解析的每个节点都是xmlNodeString,因此您需要遍历XML节点,一次匹配一个节点.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读