sitelink1  
sitelink2  
sitelink3  
sitelink4  
sitelink5  
sitelink6  
정규표현식...
 
이 얼마나 화려하며 유용하지만 더럽게 짜증나는 개념인가!!!
 
자바에서 1.4 버전부터 꾀나 다양하고 대략 강력하게 정규표현식(Regular Expression) 을 지원하는 덕분에
 
replaceAll 이라는 함수를 통해 스트링 클래스의 문자열 치환을 가볍게 할 수 있었다!
 
하지만..오늘 알게된 사실
 
JAVA 의 String.replaceAll(String regex, String replacement)메소드의 경우
 
Pattern.compile(regex).matcher(str).replaceAll(repl) 을 이용하며
 
이 경우 replacement 파라미터에 들어가면 동작이 제대로 안되는 문자가 있었다!!!!
 
Note that backslashes () and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string. Dollar signs may be treated as references to captured subsequences as described above, and backslashes are used to escape literal characters in the replacement string. (from JAVA API)
 
우연찮게도 $ 표시가 된 문자열을 치환하다 알아낸 것이다. 젠장 맞을..
 
난리를 쳤지만 결국 replacement 안에 $ 를 넣는것은 불가능해서..결국 다른 방법으로 해버렸다.
 
바로 쪼개기..ㅡ,.ㅡ..
 
split() 메소드를 이용해서 regex 를 기준으로 아예 쪼개버린후 버퍼에 그 쪼개진 부분 사이에 replacement 를 넣는 방법으로 처리
 
ㅎㅎ 야매코딩이래도~ 어쩔 수 없다~
 
더 찾아봐야 하겠지만...아무래도 저 replaceAll 메소드의 기능적 제한은 두고두고 자바사용자들의 볼멘소리의 Source 가 아닐까 싶다

 정규식을 사용하는 replaceAll 함수에서 replacement 인자로 역슬래쉬() 와 달러($)를 넣을 수가 없다.

 해서 위와 같은 문제를 해결하기 위해 임시적으로 다음과 같은 유틸성 함수를 만들어 사용하였다.

 일단은 원하는 결과를 출력해주긴 하지만 테스트케이스를 좀 더 작성해봐야 할 것 같다.

·미리보기 | 소스복사·
  1. public static String replaceAll(String source, String regex, String replacement) {   
  2.   
  3.     StringBuffer newReplacement = new StringBuffer();   
  4.     char[] replaceChar = replacement.toCharArray();   
  5.     for (int i = 0; i < replaceChar.length; i++) {   
  6.         if (replaceChar[i] == '' || replaceChar[i] == '$') {  
  7.             newReplacement.append('');   
  8.         }   
  9.         newReplacement.append(replaceChar[i]);   
  10.     }   
  11.   
  12.     return source.replaceAll(regex, newReplacement.toString());   
  13. }