기본 문법/[JAVA]
[JAVA] 정규식 표현
바켱서
2021. 9. 25. 16:41
개요
문자열에 대한 문제를 풀게 되었을 때 문자의 반복적인 Pattern나 Parsing을 해주었을 때 코드가 난잡해지는 경우가 많다.
// 카카오 문제 ) 신규 아이디 추천 _ 정규식을 적용한 코드
public static String solution(String new_id) {
String answer = "";
String temp = new_id.toLowerCase();
temp = temp.replaceAll("[^-_.a-z0-9]","");
temp = temp.replaceAll("[.]{2,}",".");
temp = temp.replaceAll("^[.]|[.]$","");
if(temp.equals(""))
temp+="a";
if(temp.length() >=16){
temp = temp.substring(0,15);
temp=temp.replaceAll("^[.]|[.]$","");
}
if(temp.length()<=2)
while(temp.length()<3)
temp+=temp.charAt(temp.length()-1);
answer=temp;
return answer;
}
// 정규식을 적용하지 않은 코드
StringBuilder sb = new StringBuilder(new_id.toLowerCase()); // 1단계
// 2단계
StringBuilder sb2 = new StringBuilder();
for(int i=0; i<sb.length(); i++){
char a = sb.charAt(i);
if((a <= _ALPA && a>=ALPA)||(a>= NUM && a<=_NUM) || a == _S || a == _END || a == _MINUS){
sb2.append(a);
}
}
// 3단계
StringBuilder sb3 = new StringBuilder();
for(int i=0; i<sb2.length(); i++){
if(sb2.charAt(i) == _END && sb2.length()-1 != i){
int j = i+1;
while(sb2.charAt(j) == _END){
if(j == sb2.length()-1) {
break;
}
j += 1;
}
i = j-1;
sb3.append(sb2.charAt(i));
}else if(sb2.charAt(i) == _END && sb2.length()-1 == i){
continue;
}else{
sb3.append(sb2.charAt(i));
}
}
// 생략..
둘의 코드의 길이만 봐도 차이가 많이 난다. 이렇게 코드를 줄이고 더 빠른 시간내에 정확하게 문제를 풀기 위해 정규식을 보게 되었다. ( + 실무 Validation에서도 많이 적용 될 수 있습니다. )
Metacharacters
Regex의 패턴에서 어떤 문자가 특별한 의미를 갖는 것을 말한다.
자주쓰는 Metacharacters를 아래에 봐보자.
출처 : https://codechacha.com/ko/java-regex/
Quantifiers
Quantifiers는 요소들을 얼마나 반복시킬지 정의한다.
출처 : https://codechacha.com/ko/java-regex/
Regex를 지원하는 String 메소드
String 클래스는 Regex를 지원하는 메소드