我正在编写Scala代码来搜索特定文件,如果reg-ex匹配则在该文件中返回该行。为简单起见,我编写了一个简单的正则表达式。 我的代码是
import scala.io.Source
import scala.util.matching
object regex {
println("Welcome to the Scala worksheet")
val patter=""".*(BEGINNING).*""".r
val dirName="/home/ugan/shaileshsir/20aug/temp.dwuKM/asup.txt"
//var n=new
//for (filen <- nt){
try {
for (line <- Source.fromFile(dirName).getLines()) {
//println(line)
line match
{
case patter(group) => group
case _ => ""
}
println(line)
}
} catch {
case ex: Exception => println("Bummer, an exception happened.")
}
虽然println(line)
工作正常并打印文件但我无法找到与正则表达式匹配的行。
任何建议都会有所帮助
答案 0 :(得分:3)
我的建议是:
GUID
如果你的正则表达式只是一个Source.fromFile(dirName).getLines().filter(_ matches ".*(BEGINNING).*")
,你也可以考虑这个:
.*{Something}.*
答案 1 :(得分:0)
import java.io._
object firstprogram {
def main(args: Array[String]) {
val regex = ".*(BEGINNING).*".r
val filename = "ScalaFile.txt"
var fileSource = scala.io.Source.fromFile(filename).getLines
print(fileSource+"\n")
for(x<-fileSource){
var fileyo=x.replaceAll(".*(BEGINNING).*","x")
val fileObject = new PrintWriter(new FileOutputStream(new File("ScalaFiletest1.txt"),true)) //true For appending
val printWriter = new PrintWriter(fileObject)
printWriter.write(fileyo+"\n") // Writing to the new file
printWriter.close()
}
}
}