2013-06-03 2 views
2

이것은 입력 문자열이며 다음 정규 표현식에 따라 5 부분으로 나눠서 5 개의 그룹을 인쇄 할 수 있지만 항상 일치하는 항목이 없습니다. . 내가 도대체 ​​뭘 잘못하고있는 겁니까 ?문자열을 5 부분으로 나눌 수있는 정규 표현식

String content="beit Be it enacted by the Senate and House of Representatives of the United States of America in Congress assembled,,<m>Surface Transportation Extension Act of 2012.,<xm>"; 

Pattern regEx = Pattern.compile("^(.*)(<m>)(.*)(<xm>)(.*)$", Pattern.MULTILINE); 
System.out.println(regEx.matcher(content).group(1)); 
System.out.println(regEx.matcher(content).group(2)); 
System.out.println(regEx.matcher(content).group(3)); 
System.out.println(regEx.matcher(content).group(4)); 
System.out.println(regEx.matcher(content).group(5)); 

답변

0
Pattern regEx = Pattern.compile("^(.*)(<m>)(.*)(<xm>)(.*)$", Pattern.MULTILINE); 
Matcher matcher = regEx.matcher(content); 
if (matcher.find()) { // calling find() is important 
// if the regex matches multiple times, use while instead of if 
    System.out.println(matcher.group(1)); 
    System.out.println(matcher.group(2)); 
    System.out.println(matcher.group(3)); 
    System.out.println(matcher.group(4)); 
    System.out.println(matcher.group(5)); 
} else { 
    System.out.println("Regex didn't match"); 
} 
+0

jlordo, 나는 궁극적으로 이것을하고 싶다 : "regEx.matcher (content) .replaceAll (replaceExpression)"과 나의 replaceExpression은 다음과 같다 : "$ 1 <marginal> $ 3 </marginal > $ 5" – Phoenix

+0

@Phoenix : 문제가 어디에 있습니까? 당신은 당신의 질문에 전혀 언급하지 않았습니다. – jlordo

+0

@jlordo : 그는 첫 번째 질문 [여기] (http://stackoverflow.com/questions/16903315/why-doesnt-the-following-regex-work-when-input-through-spring)을 요청했지만하지 않았다. 50 분 (헐떡 거림!) 동안 대답을 가지고, 그는 다른 사람에게 물었다. –

0

귀하의 정규식의 5 경기는 아무것도 일치하지 않습니다 - &lt;xm&gt; 이후에 내용이 없습니다. 또한 실제로는 regEx.matcher()을 한 번 실행 한 다음 그룹을 하나의 일치 프로그램에서 꺼내야합니다. 작성된대로 정규 표현식을 5 번 실행하여 한 번씩 각 그룹을 꺼냅니다. 또한 RegEx는 find() 또는 matches으로 전화하지 않는 한 절대 실행되지 않습니다.

+1

'find()'도'matches()'도 호출되지 않기 때문에 실제로는 정규식을 실행하지 않습니다. – jlordo

+0

좋은 지적. – Adrian

+1

'find()'와'matches()'는'Pattern'에서 호출 될 수 없습니다. – jlordo

관련 문제