(Scala 15) 文件和正则表达式

博客围绕Scala中的文件和正则表达式展开,虽未给出具体内容,但可知聚焦于Scala在文件操作及正则表达式运用方面的信息技术知识。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/**
  * 第15章 文件和正则表达式
  */
import java.io.{File, FileInputStream, PrintWriter}

import com.shuai.module_15_file_and_regex.Person15
import com.sun.xml.internal.ws.developer.Serialization

import scala.io.Source

//########################### 15.1 读取行 #################################
val source = Source.fromFile("f:/app.log", "utf-8")
val lineIterator = source.getLines()
for (line <- lineIterator) println(line)
source.close()

val source11 = Source.fromFile("f:/app.log", "utf-8")
val arr = source11.getLines().toArray
for (line <- arr) println(line)
source11.close()

//########################### 15.2 读取字符 #################################


val source2 = Source.fromFile("f:/app.log", "utf-8")
for (line <- source2) print(line + ",")
source2.close()

val source21 = Source.fromFile("f:/app.log", "utf-8")
val iter = source21.buffered
while (iter.hasNext) {
  print(iter.next() + ",")
}
source21.close()


//########################### 15.3 读取词法单元和数字 #################################
/**
  * 如果想读取以空格隔开的词法单元,可以使用如下:
  */
val source3 = Source.fromFile("f:/app.log", "utf-8")
val tokens = source3.mkString.split("\\s+")

//tokens: Array[String] = Array(#2019-05-18T03:24:45.337Z, tom, lily, salery, angle, baby, father, mother, grandpa)


//########################### 15.4 从URL或其他源读取 #################################


val source4 = Source.fromURL("http://spark.apache.org").mkString.split(" ")
val source41 = Source.fromString("www.baidu.com").mkString.split("\\.")
val source42 = Source.stdin //(从标准输入读取)控制台输入

//读取二进制文件,需要利用java方法
val file = new File("f:/app.log")
val in = new FileInputStream(file)
val bytes = new Array[Byte](file.length.toInt) //后面()是定义Array的长度
in.read(bytes)
in.close()

bytes

/**
  * scala没有内建的对写入文件的致辞.要写入文本文件,可使用java.io.PrintWriter
  */
val out = new PrintWriter("f:/app2.log")
for (i <- 1 to 100) out.println(i)
out.close()


//########################### 15.5 序列化 #################################
/**
  * 实现Serializable
  * 如果想接受缺省的ID,也可以省略掉注解@SerialVersionUID
  */

@SerialVersionUID(23L) class Person(val name: String) extends Serializable {
  override def toString = name
}


/**
  * 进行序列化和反序列化
  */

import java.io._

//序列化
val fred = new Person15("fred")

val out2 = new ObjectOutputStream(new FileOutputStream("f:/Person.serialize"))

out2.writeObject(fred)

out.close()

//反序列化
val in2 = new ObjectInputStream(new FileInputStream("f:/Person.serialize"))
val saveFred = in2.readObject().asInstanceOf[Person15]




//########################### 15.6 正则表达式 #################################

val numPattern = "[0-9]+".r

for (matchiStirng <- numPattern.findAllIn("99sdf,23dsjo2fe234"))
  print(matchiStirng + " ")


numPattern.findAllIn("99sdf,23dsjo2fe234").toArray


numPattern.findFirstIn("99sdf,23dsjo2fe234")

numPattern.replaceFirstIn("99sdf,23dsjo2fe234", "XX")
numPattern.replaceAllIn("99sdf,23dsjo2fe234", "XX")

//表达式组合
val numitemPattern = "([0-9]+) ([a-z]+)".r

//括号 提取器 原理是unapply,调用的是unapplySeq
//将num设为"99",item设为"bottles"
val numitemPattern(num, item) = "99 bottles"

for (numitemPattern(num, item) <- numitemPattern.findAllIn("99 bottles, 88 tommer"))
  print(num, item) //(99,bottles)(88,tommer)

 

<think>嗯,用户想了解在Scala中使用正则表达式进行文件读写操作的示例。我需要结合之前提供的引用内容来回答这个问题。首先,我得回忆一下Scala中处理文件读写正则表达式的基本方法。 根据引用[3],Scalascala.io.Source类用于读取文件,可以用getLines方法逐行读取,或者用mkString整个读取。记得关闭文件,或者用try语句处理异常。正则表达式方面,引用[2]提到可以用String的.r方法创建Regex对象,使用findAllIn、findFirstIn等方法匹配内容。 用户的需求是结合这两部分,即在读取文件时应用正则表达式,可能提取或处理特定模式的数据,然后写入结果到另一个文件。需要给出示例代码,比如读取文件中的数字并输出到新文件。 首先,读取文件部分,使用Source.fromFile,处理异常,关闭资源。然后对每一行应用正则表达式,比如匹配数字。写入的话,可能用Java的PrintWriter或者Scala的简化方法。引用[4]提到scala.sys.process包,但这里可能不需要,直接用文件写入的常规方法。 需要注意代码的完整性正确性。比如,读取文件后关闭资源,处理可能的异常。正则表达式示例,比如匹配数字或邮箱。写入文件时,确保正确使用写入流,并处理可能的IO异常。 可能需要两个示例:一个读取并过滤内容,另一个提取数据后写入。例如,读取日志文件中的时间戳,或者提取邮件地址并保存。需要确保代码符合Scala习惯,比如使用Try来处理异常,或者使用case语句。 另外,用户可能需要了解如何逐行处理,以及如何将整个文件作为字符串处理。比如,用getLines.toList逐行处理,或者用mkString整体处理后再用正则表达式匹配。 总结步骤:1.读取文件,2.逐行应用正则表达式,3.处理匹配结果,4.写入到新文件。代码示例要包括这些步骤,并展示不同正则方法的应用,如findAllIn、replaceAllIn等。同时,引用相关的引用来源作为支持。</think>### 如何在Scala中使用正则表达式进行文件读写操作 #### 1. 使用正则表达式读取文件并提取内容 以下示例演示如何读取文件中的数字并保存到新文件: ```scala import scala.io.Source import java.io.PrintWriter object RegexFileReadWrite { def main(args: Array[String]): Unit = { val numPattern = "[0-9]+".r // 匹配数字的正则表达式[^2] try { // 读取文件并提取数字 val source = Source.fromFile("input.txt") val matches = source.getLines() .flatMap(line => numPattern.findAllIn(line)) // 逐行匹配数字[^3] .toList source.close() // 写入匹配结果 val writer = new PrintWriter("output.txt") matches.foreach(writer.println) writer.close() println("写入完成,共找到" + matches.size + "个数字") } catch { case e: Exception => println("操作失败: " + e.getMessage) } } } ``` #### 2. 使用正则表达式过滤并修改文件内容 此示例将文件中的邮箱地址替换为星号保护隐私: ```scala import scala.io.Source import java.io.PrintWriter object EmailFilter { def main(args: Array[String]): Unit = { val emailPattern = """\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b""".r try { val source = Source.fromFile("contacts.txt") val modified = source.getLines() .map(line => emailPattern.replaceAllIn(line, "***@***")) // 替换邮箱地址[^2] .toList source.close() new PrintWriter("filtered_contacts.txt") { write(modified.mkString("\n")); close } } catch { case e: Exception => println("处理异常: " + e.getMessage) } } } ``` #### 核心要点说明 1. **文件读取**: - 使用`Source.fromFile`创建文件源对象 - 通过`getLines()`逐行处理内容[^3] - 必须调用`close()`释放资源 2. **正则操作**: - 使用`.r`方法将字符串转为正则对象[^2] - `findAllIn`返回所有匹配项的迭代器 - `replaceAllIn`实现批量替换 3. **文件写入**: - 推荐使用`PrintWriter`进行文本写入 - 注意异常处理资源关闭
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值