하위 표현 "[ ] "는 중괄호에 지정된 모든 문자와 일치합니다. 따라서 모든 대문자를 문자열의 끝으로 이동하려면 -
-
주어진 문자열의 모든 문자를 반복합니다.
-
"[A-Z] 정규식을 사용하여 지정된 문자열의 모든 대문자를 찾습니다. ".
-
특수 문자와 나머지 문자를 두 개의 다른 문자열로 연결합니다.
-
마지막으로 특수 문자 문자열을 다른 문자열에 연결합니다.
예시 1
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
다음은 Regex 패키지의 메소드를 이용하여 문자열의 대문자를 끝까지 이동시키는 자바 프로그램이다.
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);
//Creating a pattern object
Pattern pattern = Pattern.compile(regex);
//Matching the compiled pattern in the String
Matcher matcher = pattern.matcher(input);
//Creating an empty string buffer
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