2016-08-24 2 views
1

자바 코드에서 정규식을 사용하여 동적으로 문자열을 교체내가 자바 코드에서 다음과 같이 솔루션을 원하는

문자열 inputStr = "이것은 내가 좋아하는 문자열을 변환 할 샘플 @ hostname1의 @ 호스트-name2에있다 : @Test 호스트 - @ test1, 즉 달러 뒤에 열린 중괄호, 문자열 및 닫는 중괄호를 입력하십시오. ";

출력 문자열 내가 필요

출력으로 : "이것은 샘플 $ {hostname1} $ 내가 좋아하는 문자열 변환 할 {호스트 이름 2}입니다 : $ {테스트} 호스트 - $ {TEST1를}에 형식 즉, 달러 뒤에 열린 중괄호, 문자열 및 닫기 중괄호가옵니다. ";

나는

public void regEx(String intputStr){ 
     String pattern = "\\S(@)\\S+"; 
     Pattern r = Pattern.compile(pattern); 
     Matcher m = r.matcher(commands); 

     String replacePattern = " \\$\\{\\S+\\} "; 
     int i=0; 

     while(m.find()) { 
      Pattern.compile(pattern).matcher(intputStr).replaceAll(replacePattern); 
      // System.out.println(m.group(i)); 
      //i++; 
     } 
     // System.out.println(i); 
     System.out.println(intputStr); 
    } 

처럼 아래 시도하지만 진행할 수 예외하지를 얻을. 도와주세요.

답변

0

다음과 같은 한 줄 멀리 얻을 수 있습니다 :

inputStr = inputStr.replaceAll("@(.*?)\\s", "\\${$1} "); 

이 기호와 가까운 공간의 사이에있는 모든 캡처 정규식 @(.*?)\\s과 일치, 그리고 당신이 원하는 포맷으로 대체합니다.

String inputStr = "This is a sample @hostname1 @host-name2 where I want to convert the string like :@test [email protected] to format i.e dollar followed by open braces, string and close braces."; 
// add space to match term should it occur as the last word 
inputStr += " "; 
inputStr = inputStr.replaceAll("@(.*?)\\s", "\\${$1} "); 
inputStr = inputStr.substring(0, inputStr.length()-1); 

System.out.println(inputStr); 

출력 :

This is a sample ${hostname1} ${host-name2} where I want to convert the string like :${test} host-${test1} to format i.e dollar followed by open braces, string and close braces. 
+0

이 너무 briiliant입니다. 귀하의 솔루션에 감사드립니다. –

관련 문제