달력

4

« 2024/4 »

  • 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

HTML 소스에서 <img .... > 태그만 정규표현식을 이용해서 추출할 수 있다~~

Pattern.compile("<img[^>]*src=[\"']?([^>\"']+)[\"']?[^>]*>");

위의 패턴을 이용하면 된다는..

하나씩 보자.

<img
[^>]*src=[\"']?([^>\"']+)[\"']?[^>]*>
<img 태그를 찾는다.( <img......... )

<img[^>]*src=[\"']?([^>\"']+)[\"']?[^>]*>
>가 아닌 모든 것들..(<img height=100 width=50 ......)

<img[^>]*src=[\"']?([^>\"']+)[\"']?[^>]*>
src= 속성을 찾는다. (<img height=100 width=50 src=.....)

<img[^>]*src=[\"']?([^>\"']+)[\"']?[^>]*>
"나 '가 0 또는 1번 이상 나타나고, (<img height=100 width=50 src='......)

<img[^>]*src=[\"']?([^>\"']+)[\"']?[^>]*>
>나 ", '가 1 또는 그 이상 나타나며, (<img height=100 width=50 src='10.gif......)

<img[^>]*src=[\"']?([^>\"']+)[\"']?[^>]*>
"나 '가 0 또는 1번 이상 나타나고, (<img height=100 width=50 src='10.gif'......)

<img[^>]*src=[\"']?([^>\"']+)[\"']?[^>]*>
>가 아닌 모든 문자들.. (<img height=100 width=50 src='10.gif' alt='10'......)

<img[^>]*src=[\"']?([^>\"']+)[\"']?[^>]*>
> 로 끝나는 (<img height=100 width=50 src='10.gif' alt='10'>)

문자열 이라는거죠~

<img height=100 width=50 src='10.gif' alt='10'>

아래 예제를 돌려보자~~

package cis.jcaps.app;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PatternTest
{
 final static Pattern nonValidPattern  =  Pattern.compile("<img[^>]*src=[\"']?([^>\"']+)[\"']?[^>]*>");
 final static File indexFile = new File("index.html");
 
 public static void main(String[] args) {
  List<String> list = null;
  String str = null;
  StringBuilder sb = new StringBuilder();
  BufferedReader br = null;
  
  try {
   System.out.println(indexFile.exists());
   br = new BufferedReader(new FileReader(indexFile));
   while( (str = br.readLine()) != null ) {
    sb.append(str);
   }
  } catch(Exception e) {
   e.printStackTrace();
  }
  list = stripNonValidXMLCharacters(sb.toString());
  
  for(String tmp : list ) {
   System.out.println(tmp);
  }
 }

public static List<String> stripNonValidXMLCharacters(String str) {
  List<String> result = new ArrayList<String>();
  StringBuffer out = new StringBuffer();
  Matcher matcher = nonValidPattern.matcher(str);

  while (matcher.find()) {
   result.add(matcher.group(1));
  }
  matcher.appendTail(out);
  return result;
 }
}

:
Posted by 뽀기