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 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 | import java.util.regex.Matcher; import java.util.regex.Pattern; .... while ( true ){ String str = bf.readLine(); if (str == null ) break ; if (str.length() == 0 ) pw.println(); str = this .removeTag(str); System.out.println(str); } .... public String removeTag(String str){ Matcher mat; // script 처리 Pattern script = Pattern.compile( "<(no)?script[^>]*>.*?</(no)?script>" ,Pattern.DOTALL); mat = script.matcher(str); str = mat.replaceAll( "" ); // style 처리 Pattern style = Pattern.compile( "<style[^>]*>.*</style>" ,Pattern.DOTALL); mat = style.matcher(str); str = mat.replaceAll( "" ); // tag 처리 Pattern tag = Pattern.compile( "<(\"[^\"]*\"|\'[^\']*\'|[^\'\">])*>" ); mat = tag.matcher(str); str = mat.replaceAll( "" ); // ntag 처리 Pattern ntag = Pattern.compile( "<\\w+\\s+[^<]*\\s*>" ); mat = ntag.matcher(str); str = mat.replaceAll( "" ); // entity ref 처리 Pattern Eentity = Pattern.compile( "&[^;]+;" ); mat = Eentity.matcher(str); str = mat.replaceAll( "" ); // whitespace 처리 Pattern wspace = Pattern.compile( "\\s\\s+" ); mat = wspace.matcher(str); str = mat.replaceAll( "" ); return str ; } |
JAVA 에서도 정규표현식을 이용하여 패턴매칭이 가능하다.
다음은 정규표현식을 사용하여, 숫자와 영문을 제거하는 소스코드이다.
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 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | import java.util.regex.*; .... private String removeChar(String inp){ // 띄어쓰기 제거 String tmp = inp.replaceAll( " " , "" ); // 숫자 제거 tmp = this .removeRex( "[0-9]" , tmp); // 영문 제거 tmp = this .removeRex( "[a-zA-Z]" , tmp); return tmp; } // 패턴 제거 private String removeRex(String rex, String inp){ Pattern numP = Pattern.compile(rex); Matcher mat = numP.matcher( "" ); mat.reset(inp); inp = m.replaceAll( "" ); return inp ; } |
매칭된 부분을 출력
1 2 3 4 5 6 7 8 9 10 11 | Pattern script = Pattern.compile( "\\[.*\\]$" ); mat = script.matcher(str); while (mat.find()){ System.out.println(mat.group()); } |
StackOverflowError
위의 소스를 돌리다 보면 위와같은 에러가 뜬다.
그 이유는, 태그를 잘라낼 문자열의 길이가 너무 클때 생긴다고 한다. 해결방법은 없는듯하다.
문자열을 잘라내서 분류를 하던 해야하겠다.