Tcl正则表达式提取字符串部分

3
[ 22.06.2013 23:23:41 UTC ]--[&nbsp;&nbsp;&nbsp;PRE&nbsp;&nbsp;&nbsp;]--[&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="?section=0DAY" title="SHOW ONLY 0DAY">0DAY</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;]--[ <a href="?search=Aminsamples+Sexy+Melody+Vol+2+MIDI+6581">Aminsamples.Sexy.Melody.Vol.2.MIDI-6581</a> ]--<b>[ 2.30MB ]</b>--<b>[ 1F ]</b>--<span style="font-weight: bold;">[ <a href="download/Aminsamples.Sexy.Melody.Vol.2.MIDI-6581.rar" title="Aminsamples.Sexy.Melody.Vol.2.MIDI-6581.rar">DOWNLOAD</a> ]

我想获取像这样显示的数据。
[ 22.06.2013 23:23:41 UTC ]--[   PRE   ]--[      0DAY       ]--[ Aminsamples.Sexy.Melody.Vol.2.MIDI-6581 ]--[ 2.30MB ]--[ 1F ]--[ DOWNLOAD ]

但我不确定该如何做到这一点,我只能够获取的是Aminsamples.Sexy.Melody.Vol.2.MIDI-6581.rar

我希望在TCL中完成此操作

这是我当前的代码。

   catch {set http [::http::geturl http://www.prelist.ws -timeout 15000]} error
     if {[string match "*error*" $error]} { puts "connect error!" ; return 0 }
      if {[string match "*timeout*" $error]} { puts "timeout!"; return 0 }
       set html [::http::data [split $http "\n"]]
         regsub -all "&amp;" $html {\&} html
         regsub -all "&times;" $html {*} html
         regsub -all "&nbsp;" $html { } html
         regsub -all -nocase "&#215;" $html "x" html
         regsub -all -nocase "&lt;" $html "<" html
         regsub -all -nocase "&gt;" $html ">" html
         regsub -all ">" $html "" html
            regsub -all "<tt" $html "" html
    foreach line $html {
    if {[string match "*SHOW*" $line]} { continue }
    if {[string match "*title*" $line]} {
    regexp -nocase -- {title="(.*?)>} $line -> all line
    regsub -all -nocase "title=" $line {} line
    regsub -all -nocase "DOWNLOAD" $line {} line
    regsub -all -nocase "\"</a" $line {} line
    regsub -all -nocase "\"free" $line {} line
    regsub -all -nocase "\"" $line {} line
    regsub -all -nocase "\\\[" $line {} line
    regsub -all -nocase "<title" $line {} line
    regsub -all -nocase "\\\]</title" $line {} line
    puts "$line"
}
}

1
使用TCLLIB的htmlparse包解析HTML字符串,这就是它的用途。如果htmlparse::parse不能满足您的需求,请使用htmlparse::2treestruct::tree。还可以查看htmlparse::mapEscapes - potrzebie
1个回答

2

这可以很容易地使用xpath完成:

#! /usr/bin/tclsh

package require tdom

set fp [open "input.txt" r]
set html [read $fp]
close $fp

set doc [ dom parse -html $html ] 
set root [$doc documentElement]
set itemNodes [$doc selectNodes {//div[@id="list"]/tt/small}]

foreach itemNode $itemNodes {
    puts "[$itemNode asText]"
}

请注意,您可以使用此模式拆分每个字段:
foreach itemNode $itemNodes {
    set line "[string trim [$itemNode asText] \[\]\ ]"
    set fields [regexp -inline -all -- {[^[\s][^][]*?\S(?=\s*(?:]|$))} $line]
    puts [lindex $fields 2]
}

+1(特别是对于tdom):在复杂的拆分情况下,textutil::split包非常有用。 - Donal Fellows

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接