Rebol / Red 解析中的条件 "marking"

Conditional "marking" in Rebol / Red parse

如何标记第一个main div的结束(当div-count第一次为0时),而不是第二次,或者有没有办法突破解析有条件地为变量值 ?

        content: {<div class="main">
          <h1>
            Big TITLE
          </h1>
          <div>
            <section>
              <p>a paragraph</p>
            </section>
             <section>
              <p>a paragraph</p>
            </section>
              <section>
              <p>a paragraph</p>
            </section>
           </div>
           <div>
              <p>Blah Blah</p>
           </div>
        </div>
        <div>
          Another Div
        </div>

    <div class="main">
          <h1>
            Big TITLE
          </h1>
          <div>
            <section>
              <p>a paragraph</p>
            </section>
             <section>
              <p>a paragraph</p>
            </section>
              <section>
              <p>a paragraph</p>
            </section>
           </div>
           <div>
              <p>Blah Blah</p>
           </div>

        </div>
        <div>
          Another Div
        </div>    
        }

        rules: [
             thru <div class="main">
             (div-count: 1)
              some [
                "<div" (probe ++ div-count) skip
              |
                "</div>" mark:  ( probe -- div-count   if div-count = 0 [insert mark "closing main div"]) skip 
              |  skip
             ]
          ]
        parse/all content rules 

您似乎需要混合使用 optif 关键字。考虑一个简化的例子:

count: 0
div: ['div some integer! /div]

probe parse [
    div 1 2 3 /div 
    div 4 5 6 /div
    div 7 8 9 /div
][
    some [
        div (count: count + 1) opt [if (count = 1) mark:]
    ] 
]

probe mark

在这里,在每个 div 规则匹配之后,计数器会增加。之后有一个可选的匹配——如果计数器在 1,那么当前输入位置被标记,否则解析继续按原样进行。由于此规则是可选的,无论成功或失败,解析都将继续。

此外,如果您想跳出解析循环(即 someanywhile),您可以使用 break (returns 成功)或 reject(returns 失败),再次结合 optif 和条件 paren! 表达式。

这是一个在 Red 和 Rebol 中工作的解决方案,使用您的方法加上对规则的一些自我修改

rules: [
    thru <div class="main">
    (div-count: 1 clear rules/5/8 )
    some [
        "<div" (probe div-count: div-count + 1) skip
        |
        "</div>" mark:  ( 
             probe div-count: div-count - 1   
             if div-count = 0 [
                 insert mark "closing main div"  append rules/5/8 [to end]  
             ]
         ) [] skip 
         |  skip
     ]
 ]