2014-11-12 3 views
0

아래 코드를 참조하십시오. 기본적으로 파일 형식을 확인하기 위해 특정 단어를 확인하고 있습니다. 아래에서 코드를 확인하고 이것이 최선의 방법인지 알고 싶습니다. 제안해라. 파일 이름이 TEMP _data.dat 코드를 전달합니다 이상도, 내가 찾고 있어요 정확한 단어,문자열의 특정 단어를 검색하는 방법

감사를 incoming_있다

Example File Name : incoming_EMP_data.dat 
final String[] files = file.list(); 
if (files != null && files.length > 0) {     
fileName = files[0]; 
if(files[0].replace("_"," ").indexOf("EMP")!=-1) 
System.out.println("EMP file"); 
else 
System.out.println("NOT EMP file"); 
} 

경우

MKR

+0

http://stackoverflow.com/questions/3057621/java-filenames-filter-pattern -이 기능을 살펴보십시오. – BatScream

답변

0

파일 이름 패턴을 가지고 ? 내 말은, 항상 ""같이 올 것인가?

그래, 당신이 당신의 코드를 변경할 수있는 경우 :

if(files[0].indexOf("_EMP_") != -1) 

감사합니다. 예를 들어

0

캔은 정규 표현식 단어 boundary matcher\b와 함께 할 수 :

String[] examples = { 
     "incoming_EMP_data.dat", 
     "EMP.pemp", // word boundary can be beginning or end 
     "Hurz-EMP#poof", // many 
     "~EMP=", // many strange characters are boundaries 
     "XYZ_TEMP.dat", 
     "1EMP2", // numbers are considered word 
     "ßEMPö" // unicode characters are also considered word 
}; 

Pattern pattern = Pattern.compile("\\bEMP\\b"); 
// word boundary EMP word boundary 
// _ counts as part of a word though 

for (String string : examples) { 
    if(pattern.matcher(string.replace("_", " ")).find()) { 
     System.out.println(string + " is EMP"); 
    } else { 
     System.out.println(string + " is not."); 
    } 
} 

인쇄

incoming_EMP_data.dat is EMP 
EMP.pemp is EMP 
Hurz-EMP#poof is EMP 
~EMP= is EMP 
XYZ_TEMP.dat is not. 
1EMP2 is not. 
ßEMPö is not. 

좋은 점에 대한 \b는 단어 경계가 시작 경우에도이 일치한다는 것입니다 또는 문자열의 끝. 그것은 쉽게 해결되지 않는 것입니다. _은 불행히도 단어의 일부로 간주되므로 위와 같이 대체하거나 대체 패턴 "(\\b|_)EMP(\\b|_)"을 포함하도록 패턴을 확장해야합니다.

관련 문제