HTML에서 정규표현식으로 검색 질문입니다.

viper9의 이미지

정규표현식을 잘 몰라서 HTML을 파싱하는데 어렵네요.. 인터넷 뒤지며 해보다 잘 안되서 여기 있는 고수님들의 조언 좀 부탁드립니다.

HTML 안에 다음과 같은 코드가 들어가 있습니다.

...............(중략)..........
 
<div style="width:100px" class="target1">
 
        <h1><a href="http://target2.com" target="_blank">target3</a></h1>
 
        <span style="white-space:nowrap;">blahblah<a href="http://aslkdj.com/a.html"  target="_blank"><img alt="" src="http://a.com.gif" class="sfolder absmid" style="margin-right:3px;background-color:#FFFFFF" />blahblah</a></span>
 
</div>
 
...............(중략)..........

제가 뽑아내고 싶은건 http://target2.com 이라는 문자열과 target3 라는 문자열 두개입니다.

생각해본 조건은 다음과 같습니다.

http://target2.com 이라는 문자열을 뽑아내려면...

1. div 태그로 된 부분 중에 class가 target1인 곳 중에서
2. h1이라는 태그로 감싸진 곳 중에서
3. a href= 안에 있는 문자열

target3 라는 문자열을 뽑아내려면...

1. div 태그로 된 부분 중에 class가 target1인 곳 중에서
2. h1이라는 태그로 감싸진 곳 중에서
3. 태그로 감싸진 곳

인것 같습니다.

'사이에 있는'이라는 표현을 정규표현식으로 어떻게 나타내는지만 알아도 도움이 될것 같은데 인터넷을 아무리 뒤져도 어떤 두 단어 사이에 있는 부분을 검색하는 정규표현식을 설명해준 곳이 없네요.. 혹시 이것만이라도 가르쳐주셔도 정말 감사합니다.

raymundo의 이미지

"정규표현식"과 "캡쳐" 두 가지 키워드로 검색해보세요. capture 는 한글로 쓰면 캡쳐 캡처 캡춰 등등 여러 가지가 나오겠습니다만.

Perl이라면,
http://gypark.pe.kr/wiki/Perl/정규표현식
1.1.5 섹션에 나와 있습니다.

아마 다른 언어들도 웬만하면 캡처할 부분을 괄호로 둘러싸고, 매치될 경우 왼쪽 괄호부터 번호가 1,2,... 이런 식으로 붙는다는 건 비슷비슷할 겁니다.

# $str 에 저 html 텍스트가 들어있다고 치고
 
# 링크만 가지고 뽑는다면
if ( $str =~ m'<h1><a href="(.*?)" target="_blank">(.*?)</a></h1>' ) {
    print "1 [$1]\n2 [$2]\n";
}
 
# div 태그까지 다 따진다면
if ( $str =~ m'<div[^>]*class="target1"[^>]*>.*?<h1><a href="(.*?)" target="_blank">(.*?)</a></h1>.*?</div>'s ) {
    print "3 [$1]\n4 [$2]\n";
}

1 [<a href="http://target2.com" rel="nofollow">http://target2.com</a>]
2 [target3]
3 [<a href="http://target2.com" rel="nofollow">http://target2.com</a>]
4 [target3]

근데 하시려는 게 정규식 공부가 아니라 html에서 데이타 추출하는 거라면 그런 용도의 라이브러리를 쓰시는 게 훨씬 편할 겁니다. 정규식은 html 이 예상과 조금만 달라져도 동작을 안 하기 일쑤라서...

좋은 하루 되세요!

lacovnk의 이미지

윗분 말씀대로, HTML 파싱해서 처리하려면 정규식이 아니라 라이브러리를 쓰세요. XPATH 나 CSS selector 를 이용할 수 있습니다.

Ruby라면 nokogiri가 있습니다.

require 'nokogiri'
 
html = '<div style="width:100px" class="target1">
  <h1><a href="http://target2.com" target="_blank">target3</a></h1>
  <span style="white-space:nowrap;">blahblah<a href="http://aslkdj.com/a.html"  target="_blank"><img alt="" src="http://a.com.gif" class="sfolder absmid" style="margin-right:3px;background-color:#FFFFFF" />blahblah</a></span>
</div>'
 
doc = Nokogiri::HTML(html)
 
puts doc.at('div.target1 h1 a')['href']
puts doc.at('div.target1 h1 a').text

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.