
我想要一個替代解決方案這個 jQuery 駭客,嚐嚐重新發明輪子的滋味 - 看起來我確信我可以使用基本的 *ix 工具通過一些單行代碼來完成此操作。看起來更簡單、更直接的方法是找到所有附加有 px, some \d+px
-match 的數字,然後將其與一個常數相乘,但\d
會失敗 - 僅當前面沒有數字時才匹配[^\d]\d+px
,然後進行替換/乘法。
最簡單、最優雅的解決方案獲勝,如何進行匹配-乘法-替換?
我使用 Vim,但樂於接受新想法。
答案1
bash-4.2$ cat map.htm
<map name="world">
<area shape="rect" coords="0%,0%,32%,32%" >
<area shape="rect" coords="8%,40%,50%,80%" >
<area shape="rect" coords="56%,4%,84%,18%" >
<area shape="rect" coords="74%,20%,90%,40%" >
<area shape="rect" coords="70%,42%,96%,62%" >
<area shape="rect" coords="0%,74%,70%,95%" >
</map>
bash-4.2$ perl -pe '$w=640;$h=480;s!(\d+)%,(\d+)%,(\d+)%,(\d+)%!($1*$w/100).",".($2*$h/100).",".($3*$w/100).",".($4*$h/100)!ge' map.htm
<map name="world">
<area shape="rect" coords="0,0,204.8,153.6" >
<area shape="rect" coords="51.2,192,320,384" >
<area shape="rect" coords="358.4,19.2,537.6,86.4" >
<area shape="rect" coords="473.6,96,576,192" >
<area shape="rect" coords="448,201.6,614.4,297.6" >
<area shape="rect" coords="0,355.2,448,456" >
</map>
當然,這在某些情況下會失敗,因為正規表示式不是解析 HTML 的方法,如得出結論SO。但使用專用的 HTML 解析器解決問題將不再是一件簡單的事。
但是,如果您確定與座標對的純文字不會發生衝突,您甚至可以將其簡化為:
perl -pe '$w=640;$h=480;s!(\d+)%,(\d+)%!int($1*$w/100).",".int($2*$h/100)!ge' map.htm