java,grep
<link rel="stylesheet" href="https://js.how234.com/third-party/SyntaxHighlighter/shCoreDefault.css" type="text/css" /><script type="text/javascript" src="https://js.how234.com/third-party/SyntaxHighlighter/shCore.js"></script><script type="text/javascript"> SyntaxHighlighter.all(); </script>
grep java是什麼,讓我們一起了解一下?
grep是一種強大的文本搜索工具,它能使用特定模式匹配(包括正則表達式)搜索文本,並默認輸出匹配行。grep的工作方式在一個或多個文件中搜索字符串模板。
Grep命令中允許指定的串語句是一個規則表達式,這是一種允許使用某些特殊鍵盤字符的指定字符串的方法,這種方法中的特殊鍵盤字符可以用於代表其他字符也可以進一步定義模式匹配工作方式。
那麼java正則表達是如何對grep功能進行實現的?
我們以檢查test.txt文件裏每一行,將開頭是test的行打印出來為例:
package com.company;import java.io.*;import java.util.Scanner;import java.util.regex.Matcher;import java.util.regex.Pattern;public class Main { public static void main(String[] args) throws IOException{ String str; String pattern; System.out.println("請輸入你要查詢的內容:(^表示開頭含有此字符串,$表示結尾含有此字符串)"); Scanner input=new Scanner(System.in); pattern=in //利用正則表達式輸入要查詢的內容,按題目要求應輸入^test BufferedReader brf=new BufferedReader(new FileReader("/home/zyf/桌面/test.txt")); System.out.println("原文本為:"); while((str=brf.readLine())!=null) { System.out.println(str); }//打印出原文本的所有內容 Grep(pattern,"/home/zyf/桌面/test.txt");//調用Grep函數 } //Grep函數 public static void Grep (String pattern,String path) throws IOException //pattern為所匹配的字符串,path為文件地址 { int number=0; Pattern r = Pattern.compile(pattern); File file=new File(path); InputStreamReader read = new InputStreamReader(new FileInputStream(file)); BufferedReader bufferedReader = new BufferedReader(read);//創建一系列類 String line = null; System.out.println("含有test的行有:"); while ((line=bufferedReader.readLine()) != null) { number++; Matcher m=r.matcher(line); if(m.find()) { System.out.println(number+"."+m.group()); } } } }