2012-06-30 2 views
0

// pattern 20xx/xx/xx, e.g. 2012/2/22 
String Regex_Date_1 = "20\\d\\d/\\d{1,2}/\\d{1,2}"; 

String cell = "from 2011/7/31 to 2011/8/15 15:10-17:40,18:30-21:00"; 
System.out.println(cell); 

System.out.println("--- a ---"); 
System.out.println(cell.matches(Regex_Date_1)); 

System.out.println("--- b ---"); 
Pattern p = Pattern.compile(Regex_Date_1); 
Matcher m = p.matcher(cell); 
while(m.find()){ 
    System.out.println(m.group(0)); 
} 

결과 :string.matches와 pattern.matches가 다른 결과를 얻는 이유는 무엇입니까?

string.matches는 false를 돌려 왜

from 2011/7/31 to 2011/8/15 15:10-17:40,18:30-21:00 
--- a --- 
false 
--- b --- 
2011/7/31 
2011/8/15 

? pattern.matches는 일치를 얻을 수 있습니까?

답변

0

String#matchestrue "이 문자열이 주어진 정규식과 일치하는 경우에만"을 반환합니다.

String#matches 그러나 Matcher#findtrue 돌아갑니다 "경우에 한해, 입력 순서의 서브 순서가이 정규 표현의 패턴과 일치": 현재 문서를 확인할 수 있습니다. 설명서는 Matcher#find에서 확인할 수 있습니다.

그래서 정리해 - String#matches true를 반환 문자열의 일부 서브가 정규식과 일치 할 수있는 경우 전체 문자열이 true 정규식과 Matcher#find 리턴으로 일치하는 경우.

+0

감사합니다. 내 질문은 -> System.out.println (cell.matches (". * ("+ Regex_Date + "). *")); –

+0

나는 정말로 그렇게 생각하지 않는다. '. *'는 모든 것을 탐욕스럽게 매치 할 것이므로 나머지 정규 표현식은 무시 될 것이다. 원하는 것을 정확히 일치시키기 위해서는'. * '를 사용해야합니다. – asenovm

0

Becucase

Regex_Date_1 = "20 \ D \ D/\ D {1,2}/\ D {1,2}"; 정규 표현식은 전체 입력 문자열과 일치하는 경우에만

matches (String regularExpression)

그의 메소드는 true를 돌려줍니다. A common mistake is to assume that this method behaves like contains(CharSequence); if you want to match anywhere within the input string, you need to add .*을 정규 표현식의 처음과 끝 부분에 추가하십시오.

+0

고마워, 가끔은 추가 할 필요가 없습니다. *, 내 경우에는 정규 표현식. * (my-regex). * –

관련 문제