다음 정규식은 모든 특수 문자, 즉 영어 알파벳 공백 및 숫자를 제외한 모든 문자와 일치합니다.
"[^a-zA-Z0-9\\s+]"
모든 특수 문자를 주어진 줄의 끝으로 이동하려면 이 정규식을 사용하여 모든 특수 문자를 일치시키고 빈 문자열로 연결하고 나머지 문자를 다른 문자열로 연결합니다. 마지막으로 이 두 문자열을 연결합니다.
예시 1
public class RemovingSpecialCharacters {
public static void main(String args[]) {
String input = "sample # text * with & special@ characters";
String regex = "[^a-zA-Z0-9\\s+]";
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 special characters#*&@
예시 2
다음은 Regex 패키지의 메소드를 이용하여 문자열의 특수문자를 끝까지 이동시키는 자바 프로그램이다.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String args[]) {
String input = "sample # text * with & special@ characters";
String regex = "[^a-zA-Z0-9\\s+]";
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 # text * with & special@ characters Result: sample text with special characters#*&@