2012-10-16 2 views
0

"내 이름 [이름], 내 도시 [cIty], 우리 나라 [countrY] .........."와 같은 문자열이 있습니다.문자열을 바꾸는 방법

대괄호 안에있는 모든 문자를 [<value in upper or lower case>]에서 [<value in lowercase>]으로 변환하고 싶습니다.

예 :에 [도시] [도시]

어떻게 Java 또는 그루비에 적은 코드와 효율적인 방법으로이 작업을 수행하려면?

편집 : 대괄호 안의 문자 만 대괄호 밖의 다른 문자가 아닌 소문자로 변환하고 싶습니다.

답변

1

다음은 원하는대로 수행 할 수있는 멋진 코드입니다.

,
def text = "My name [name], my city [cIty], my country [countrY]." 
text.findAll(/\[(.*?)\]/).each{text = text.replace(it, it.toLowerCase())} 

assert text == "My name [name], my city [city], my country [country]."  
+0

쿨! :-) 또한 루프에'text' 변수를 반복적으로 설정할 필요가없는 대답에 대한 더 짧은 경로가 있습니다 : http://stackoverflow.com/a/12932736/6509 :-) –

1

는 그루비에 익숙하지 않은,하지만 자바에서, 당신은 여기에 string.toLowerCase()

+0

내가 내 게시물을 편집 한이 모습을 – n92

4

를 사용하여 당신을 위해 일을 할 것입니다 자바 코드라고 할 수 있습니다

String str = "My name [Name], My city [cIty], My country [countrY]."; 
Matcher m = Pattern.compile("\\[[^]]+\\]").matcher(str); 
StringBuffer buf = new StringBuffer(); 
while (m.find()) { 
    String lc = m.group().toLowerCase(); 
    m.appendReplacement(buf, lc); 
} 
m.appendTail(buf); 
System.out.printf("Lowercase String is: %s%n", buf.toString()); 

출력 :

Lowercase String is: My name [name], My city [city], My country [country]. 
0
import java.util.regex.*; 


public class test { 

public static void main(String[] args) { 
    String str = "My name [name], my city [cIty], my country [countrY].........."; 
    System.out.println(str); 

    Pattern pattern = Pattern.compile("\\[([^\\]]*)\\]"); 
    Matcher matcher = pattern.matcher(str); 

    while (matcher.find()) { 
     str = str.substring(0,matcher.start()) + matcher.group().toLowerCase() + str.substring(matcher.end()); 
    } 
    System.out.println(str); 
} 

} 
2

더 짧은 그루비 경로는 다음과 같습니다

def text = "My name [name], my city [cIty], my country [countrY]." 
text = text.replaceAll(/\[[^\]]+\]/) { it.toLowerCase() } 
관련 문제