내가 찾은 모든 예는 사람들이 정규식 패턴을 검색하고 찾은 모든 그룹을 특정 값 또는 검색된 문자열의 알려진 수의 그룹으로 대체해야하는 경우에 대한 것입니다.
하지만 제 경우에는 발견 된 값에 따라 각 그룹을 변경해야합니다. 변경된 각 결과 값을 어떻게 변경할 수 있습니까?
이것이 내가 시도한 것입니다.
Pattern pattern = Pattern.compile(DEFINITION_WITH_OR);
Matcher matcher = pattern.matcher(s);
StringBuffer sb = new StringBuffer();
while (matcher.find()){
String ss = matcher.group();
/*Some string manupilation*/
// matcher.appendReplacement(sb, bestMatchedDefinition);
// matcher.appendReplacement(sb,Matcher.quoteReplacement(ss));
// s = s.replace(s.substring(matcher.start(),matcher.end()),ss);
}
내가 원하는 것은 발견 된 모든 그룹을 반복하고 발견 된 그룹에 대해 몇 가지 작업을 수행하고 해당 그룹 만 편집하는 것입니다. 실행하기 전에 콘텐츠 및 그룹 수를 알 수 없습니다.
지금까지의 모든 시도가 모든 것을 변경했거나 전혀 변경하지 않았거나 제안 사항이 있습니까?
문자열로하는 일은로 분할 |
하고 가장 짧은 부분을 가져 와서 중괄호를 제거하는 것입니다. 예제 입력 문자열 : 참고 : 다음 입력 문자열은 최종 결과가 무엇인지 보여주기위한 단순화입니다. 전체 문자열에는 많은 부분이 있습니다. 더 성가신 문자는 DEFINITION_WITH_OR
패턴을 사용하여 지 웠습니다.
a commissioned general officer in the United States Army,
[[United States Marine Corps|Marine Corps]],
or [[United States Air Force|Air Force]] superior to a lieutenant general.
A general is equal in rank or grade to a four star admiral. In the US Army,
a general is junior to a general of the army. In the US Marine Corps,
a general is the highest rank of commissioned officer. In the US Air Force,
a general is junior to a general of the air force.
다음과 같이 출력해야합니다.
a commissioned general officer in the United States Army,
Marine Corps,
or Air Force superior to a lieutenant general.
A general is equal in rank or grade to a four star admiral. In the US Army,
a general is junior to a general of the army. In the US Marine Corps,
a general is the highest rank of commissioned officer. In the US Air Force,
a general is junior to a general of the air force.
공군 과 해병대 조금 신경 쓰세요
글쎄, Joop의 답변 덕분에 다음 코드를 추가하지 않았다는 것을 깨달았습니다.
matcher.appendTail(sb);
s = sb.toString();
while 루프 후 라인 matcher.appendReplacement(sb,Matcher.quoteReplacement(ss));
이 트릭을 수행했습니다. 어떤 이유로도 matcher.appendReplacement(sb,ss);
효과가 있었지만 훨씬 느립니다. 누구든지 이유를 알고 댓글을 달 수 있다면 좋을 것입니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다