정규 표현식에서 하위 표현식 "[ ]"는 중괄호 안에 지정된 모든 문자와 일치합니다. 따라서 문자열에 포함된 모든 대문자를 문자열 끝으로 이동하려면 다음 절차를 따르면 됩니다.
주어진 문자열의 모든 문자를 하나씩 반복하며 확인합니다.
정규 표현식 [A-Z]를 사용하여 문자열 내의 모든 대문자를 찾아냅니다.
찾아낸 대문자들과 나머지 문자들을 서로 다른 두 개의 문자열로 분리합니다.
마지막으로 대문자 문자열을 나머지 문자열 뒤에 연결합니다.
예제 1: matches() 메서드 활용
다음은 String 클래스의 matches() 메서드를 이용해 문자열 속 대문자를 끝으로 이동하는 Java 프로그램입니다.
public class RemovingSpecialCharacters {
public static void main(String args[]) {
String input = "sample B text C with G upper case LM characters in between";
String regex = "[A-Z]";
String specialChars = "";
String inputData = "";
for(int i=0; i< input.length(); i++) {
char ch = input.charAt(i);
if(String.valueOf(ch).matches(regex)) {
specialChars = specialChars + ch;
} else {
inputData = inputData + ch;
}
}
System.out.println("Result: "+inputData+specialChars);
}
}실행 결과
Result: sample text with upper case characters in betweenBCGLM
예제 2: Pattern·Matcher 클래스 활용
다음은 java.util.regex 패키지의 Pattern과 Matcher 클래스를 사용하여 문자열의 대문자를 끝으로 이동하는 Java 프로그램입니다.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String args[]) {
String input = "sample B text C with G upper case LM characters in between";
String regex = "[A-Z]";
String specialChars = "";
System.out.println("Input string: \n"+input);
//패턴 객체 생성
Pattern pattern = Pattern.compile(regex);
//컴파일된 패턴을 문자열에 적용
Matcher matcher = pattern.matcher(input);
//빈 StringBuffer 생성
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
specialChars = specialChars+matcher.group();
matcher.appendReplacement(sb, "");
}
matcher.appendTail(sb);
System.out.println("Result: \n"+ sb.toString()+specialChars );
}
}실행 결과
Input string: sample B text C with G upper case LM characters in between Result: sample text with upper case characters in betweenBCGLM
두 가지 방식 모두 동일한 결과를 출력합니다. 다만 Pattern과 Matcher를 사용하면 반복적인 치환이나 더 복잡한 정규식 처리가 필요할 때 훨씬 유연하게 확장할 수 있다는 장점이 있습니다.