java正則匹配

來源:互聯網
上載者:User

標籤:java Regex 匹配 中文 數字 txt文本讀取

javaRegex列印出匹配的資料

相關知識點

java正則匹配中文

java正則匹配數字

java讀取text檔案

import java.io.BufferedReader;import java.io.File;import java.io.FileInputStream;import java.io.InputStreamReader;import java.util.HashSet;import java.util.Set;import java.util.regex.Matcher;import java.util.regex.Pattern;public class PraseSort0htm {public static void main(String[] args) {String regEx = "[\u4E00-\u9FA5]{1,}[@#]{1,}/Sort-0-[0-9]{1,}.htm"; // 正確匹配中文String str = "奇異果@#/Sort-0-012345.htm,橙子@#/Sort-0-012345.htm,蘋果@#/Sort-0-012345.htm,熱帶水果@#/Sort-0-012345.htm,";Pattern pat = Pattern.compile(regEx);Matcher mat = pat.matcher(str);while (mat.find()) {System.out.println(mat.group(0));}System.out.println("xxxxxxxxxxxxxxxxx");String filePath = "d:/xxxx.txt";readTxtFile(filePath);}public static void readTxtFile(String filePath) {try {Set<String> idSet = new HashSet<String>();Set<String> nameSet = new HashSet<String>();String regEx = "[\u4E00-\u9FA5]{1,}[@#]{1,}/Sort-0-[0-9]{1,}.htm"; // 正確匹配String regEx2 = "[0-9]{2,}";String regEx3 = "[\u4E00-\u9FA5]{1,}";Pattern pat = Pattern.compile(regEx);Pattern pat2 = Pattern.compile(regEx2);Pattern pat3 = Pattern.compile(regEx3);String encoding = "gbk";File file = new File(filePath);if (file.isFile() && file.exists()) { // 判斷檔案是否存在InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);// 考慮到編碼格式BufferedReader bufferedReader = new BufferedReader(read);String lineTxt = null;int i = 1;while ((lineTxt = bufferedReader.readLine()) != null) {// System.out.println(lineTxt);Matcher mat = pat.matcher(lineTxt);while (mat.find()) {// System.out.println(mat.group(0));//驗證可以列印成功String temp = mat.group(0);Matcher mat2 = pat2.matcher(temp);String id = "";while (mat2.find()) {id = mat2.group(0);}if (idSet.add(id)) {System.out.print(id);} else {break;}System.out.print("\t");Matcher mat3 = pat3.matcher(temp);while (mat3.find()) {System.out.print(mat3.group(0));}System.out.print("\n");i++;}}// System.out.println(i);read.close();} else {System.out.println("找不到指定的檔案");}} catch (Exception e) {System.out.println("讀取檔案內容出錯");e.printStackTrace();}}}


本文出自 “夢裡不知身是客” 部落格,謝絕轉載!

java正則匹配

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.