티스토리 뷰

자바 프로그램 언어에서 쉬워보이면서도 항상 말썽이고, 성가신 존재가 문자열이다. 문자열(String)을 특정 길이만큼 자르고(substring), 맨마지막에 계속 붙이고(append), 특정 문자열을 찾아서 바꾸고(replace), 포맷에 맞게 조립하고.. 자바에서는 String을 제어를 잘해야 좋은 프로그램이며, String 처리를 소홀히 하면 할수록 배치성 프로그램에서는 속도차이가 심하게 나기도 한다.

 

단순 공백제거를 해보자. 앞뒤, 중간 상관없이 말이다.

String s1 = "가나다 라마바   123\t456\n789"; 
System.out.println(s1.replaceAll(" ", ""));

 

 

출력되는 걸 보니, 단순하게 " "를 ""로 바꾸게 되면, 탭이나 개행문자는 제거가 되지 않는다.

 

 

 

 

문자열에는 단순 한칸짜리 스페이스가 아닌 여러가지 공백이 존재한다. 그런 것들을 일일이 지우려고 나열하기 보단 정규식으로 깔끔하게 정리가 가능하다. 정규식을 알고나면 신세계가 펼쳐지므로, 꼭 알아두어야 할 요소이다. 우선 String 객체의 replaceAll 의 doc 파일을 보면,

 

public String replaceAll(String regex, String replacement)

Replaces each substring of this string that matches the given regular expression with the given replacement.

An invocation of this method of the form str.replaceAll(regex, repl) yields exactly the same result as the expression

    Pattern.compile(regex).matcher(str).replaceAll(repl)

Note that backslashes (\) and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string; see Matcher.replaceAll. Use Matcher.quoteReplacement(java.lang.String) to suppress the special meaning of these characters, if desired.

Parameters:
    regex - the regular expression to which this string is to be matched
    replacement - the string to be substituted for each match

 

파라메터 첫번째(regex)에 찾고 싶은 문자열을 넣어도 되지만.. 원래는 정규식(regular expression)을 입력하라고 설명되어 있다. java doc 에 링크를 따라가서, java.util.Pattern 클래스의 설명을 읽어보면 정규식에 대한 설명이 잘 나와있다.

 

http://docs.oracle.com/javase/8/docs/api/index.html?java/util/regex/Pattern.html

 

위 페이지에서 가서 읽다보면,

 

Predefined character classes
. Any character (may or may not match line terminators)
\d A digit: [0-9]
\D A non-digit: [^0-9]
\s A whitespace character: [ \t\n\x0B\f\r]
\S A non-whitespace character: [^\s]
\w A word character: [a-zA-Z_0-9]
\W A non-word character: [^\w]

 

\s 라는게 있다. 이걸이용하면 ' '(스페이스), \t, \n, \x0b, \f, \r 들을 찾을 수 있다.

String s1 = "가나다 라마바   123\t456\n789"; System.out.println(s1.replaceAll("\\s", "")); 

 

출력해보면,

 

 

드디어 중간공백 포함 탭, 개행문자들이 사라지고 모두 붙어 있는 문자열을 출력했다. 이렇게 정규식을 사용할때, String 객체의 replaceAll 메소드를 사용해도 되지만, Pattern.compile(regex).matcher(str).replaceAll(repl) 로 바꾸어 사용할 수도 있다.

String s1 = "가나다 라마바   123\t456\n789"; 
String result = Pattern.compile("\\s").matcher(s1).replaceAll(""); 
System.out.println(result);

출력해보면 공백제거가 잘되어 출력된다. 동일한 기능의 코딩임을 알 수 있다. 단 특수문자에 있는 전자로된 스페이스(2byte)는 지워지지 않으므로 [ ] 를 이용해서 추가해서 정규식을 확장하여, replace 처리하면 될 것이다. 아니면 \u3000 으로 붙여넣어도 된다.

반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함