Java如何使用正則表達式查找指定字符串
對于一個文件名的使用經(jīng)常要做一些判斷,比如文件名是否是指定的名字,或者文件是否為指定的類型,或者篩選出以指定后綴結尾的文件名,等等
這時就可以提取出文件名的字符串進行比較判斷篩選
在java中的String類的一些常用方法中給出了這些工具方法,比如判斷兩個字符串是否一致,字符串是否以指定的前綴開始,字符串是否以指定的后綴結束等等方法
這里用到的java中的String類的常用方法
boolean equals(Object obj):比較字符串是否相同
boolean endWith(String str):測定字符串是否以指定的后綴結束
通過這兩個方法進行篩選
String par1 = “params.txt”;
String par2 = “_depth.dep”;
String par3 = “_GRD.grd”;
String par4 = “_cs.dep”;
String par5 = “_Tide.txt”;
String par6 = “Jonswap.txt”;
判斷文件名是否為params.txt,Jonswap.txt,或者以指定的后綴_depth.dep,_GRD.grd,_cs.dep,_Tide.txt結尾的文件
public class FileTest {
public static void main(String[] args) {
String par1 = "params.txt";
String par2 = "_depth.dep";
String par3 = "_GRD.grd";
String par4 = "_cs.dep";
String par5 = "_Tide.txt";
String par6 = "Jonswap.txt";
while(true) {
Scanner scanner = new Scanner(System.in);
System.out.println("please pressure a filename:");
String next = scanner.next();
if ("exit".equals(next)){
break;
}else if(par1.equals(next) || par2.endsWith(next) || par3.endsWith(next)
|| par4.endsWith(next) || par5.endsWith(next) || par6.equals(next))
{
System.out.println("找到了你輸入的文件:" + next);
}else{
System.out.println("沒有找到!");
}
}
}
}
以上代碼雖然可以正常運行輸出,但是它不僅匹配了后綴,只要是最后一個字母一樣的它都可以匹配上,所以多多少少有一點bug,這里的解決方法是使用正則表達式的方法,在java中的String類中也提供了使用正則表達式匹配的方法
boolean mathes(String regex):告知此字符串是否匹配給指定的正則表達式
首先了解必須的正則表達式原則
** . :通配所有的字符**
** * :匹配0次或者多次前面出現(xiàn)的正則表達式**
** + :匹配1次或者多次前面出現(xiàn)的正則表達式**
** ?:匹配0次或者1次前面出現(xiàn)的正則表達式**
** re1 | re2 :匹配正則表達式re1或者re2**
所以在制定后綴的正則表達式寫法:
.*_cs//.dep
上面代碼就是匹配后綴為_cs.dep,前面可以有內容,也可以沒有內容的文件名
.*_cs//.dep|.*_GRD.grd
上面代碼就是匹配兩個正則表達式,或者re1或者re2
了解了這兩個寫法之后,就可以進行匹配了:
public class RegexTest2 {
public static void main(String[] args) {
String regex = ".*_GRD\\.grd|.*_cs\\.dep|.*_depth\\.dep|" +
".*_Tide\\.txt|params\\.txt|Jonswap\\.txt";
while(true){
Scanner scanner = new Scanner(System.in);
System.out.print("please preesure a fileName:");
String next = scanner.next();
if (next.matches(regex)){
System.out.println("找到了:" + next);
}else if("exit".equals(next)){
System.out.println("byebye...");
break;
}else{
System.out.println("沒有找到!");
}
}
}
}
以上就完成了!
總結
到此這篇關于Java如何使用正則表達式查找指定字符串的文章就介紹到這了,更多相關Java查找指定字符串內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
使用SpringCloudApiGateway之支持Cors跨域請求
這篇文章主要介紹了使用SpringCloudApiGateway之支持Cors跨域請求的操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-07-07
springcloud干貨之服務注冊與發(fā)現(xiàn)(Eureka)
這篇文章主要介紹了springcloud干貨之服務注冊與發(fā)現(xiàn)(Eureka) ,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-01-01
解決?IDEA?Maven?項目中"Could?not?find?artifact"?
這篇文章主要介紹了解決IDEA Maven項目中Could not?find?artifact問題的常見情況和解決方案,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-07-07

