當前位置:生活全書館 >

IT科技

> java grep

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命令中允許指定的串語句是一個規則表示式,這是一種允許使用某些特殊鍵盤字元的指定字串的方法,這種方法中的特殊鍵盤字元可以用於代表其他字元也可以進一步定義模式匹配工作方式。

grep java

那麼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());                }            }        }    }

標籤: grep java
  • 文章版權屬於文章作者所有,轉載請註明 https://shqsg.com/dianzi/rrzx05.html