4

我有一个 HTML 页面,我需要替换其中的几行。但是,使用replace似乎找不到比单行更大的东西。

这是我想替换的(页面中有多个实例):

....
<div class="logo">
    <img src="resources/logo.svg" />
    <span>e</span>
    <span class="text">Market</span>
</div>
...

这是我正在尝试的代码,但它不起作用:

index-html: read %index.html    

logo-div: {<div class="logo">
<img src="resources/logo.svg" />
<span>e</span>
<span class="text">Market</span>
</div>}

new-div: {...}

out: replace/all index-html logo-div new-div

write %index.html out

^/在我的字符串中包含logo-div表示换行符并没有帮助。

我怎样才能找到整个字符串?

(我正在使用 Rebol2,但我认为 Rebol3 中的功能将相同或非常相似。)

4

2 回答 2

4

我不确定,replace但这是一个很好的parse工作机会:

index-html: read %index.html
out: copy ""
new-div: "..."

;;parse rules

title: [
    {<div class="logo">} thru {</div>} (append out new-div) ;;appends replacement when it finds that class
]

rule: [
    some [
        title |
        copy char skip (append out char)  ;;copies every other char char
    ]
]

parse index-html rule

write %index.html out

没有索引文件,但这应该可以。花一些时间仔细研究字符串解析。它非常强大。

于 2014-11-20T02:51:39.410 回答
2

我怀疑您面临的问题是元素之间的空格数可变。如果您可以修剪空白,则替换应该可以工作:

>> data: {
{    line 1     
{    line 2  
{    line 3
{    line 4   
{    <div>
{    line d1   
{    line d2
{    </div>
{    line 5    
{    line 6                   
{    }
== {
line 1     
line 2  
line 3
line 4   
<div>
line d1   
line d2
</div>
line 5    
line 6                   
}
old-div: {                
{    <div>
{    line d1   
{    line d2
{    </div>
{    }
== {
<div>
line d1   
line d2
</div>
}
>> new-div: {
{    <div>new line d1^/new line d2</div>
{    }
== "^/<div>new line d1^/new line d2</div>^/"
>> replace/all trim/all data trim/all old-div new-div
== {line1line2line3line4
<div>new line d1
new line d2</div>
line5line6}
>> data
== {line1line2line3line4
<div>new line d1
new line d2</div>
line5line6}

如果您想保留 HTML 缩进,那么按照 kealist 的建议进行解析可能是最好的选择。

于 2014-11-20T03:21:30.547 回答