簡體   English   中英

Scala正則表達式過濾器包裝的元素

[英]scala regex filter wrapped elements

我輸入的字符串形式如下所示

ellipse {
    attribute = foo

    ellipse {
        attribute = foo
        line {
            attribute = foo
            attribute = foo
            attribute = foo
        }
        line {
            attribute = foo
            attribute = foo
        }
    }
}

基本上,它是關於2d元素的,它們能夠在其中容納其他2d元素。 我的任務是編寫一個正則表達式,可以將父元素與子元素分開,以便可以分別解析它們。 如果是:

rectangle1{
    attribute = foo
}
ellipse1{
    attribute = foo
    ellipse{
        rectangle{
            attribute = foo
        }
    }
}

我希望能夠regex.findAllIn(string)然后只有矩形1和ellipse1字符串,所以我可以解析它們。 我不是使用正則表達式的專家,但我進行了嘗試,但是失敗了:

我試過了:

(?s)(?!((橢圓|點|線)\\\\ {))。+ (橢圓|點|線) \\\\ {。* \\\\}

得到所有的橢圓或點或線,

(?s)(?!((橢圓|點|線)\\\\ {))。+(橢圓|點|線) \\\\ {。* \\\\}

包括一些東西,但是

(?s) (?!( (橢圓|點|線)\\\\ {))。+(橢圓|點|線)\\\\ {。* \\\\}

(?s) (?!((橢圓|點|線)\\\\ {)) 。+(橢圓|點|線)\\\\ {。* \\\\}

在其上方有“橢圓{”“點{”之類的內容,

但這不起作用...

最有可能做我想要的事情,但是正如我所說,我不是正則表達式專家。 如果您有我的答案,我將不勝感激,因為我想了解解決方案。 先感謝您!

純正則表達式不太適合此任務。 您必須使用遞歸正則表達式,而Java(因此也包括Scala)目前不支持它們。

但是,在使用Scala時,您可以利用強大的Parser Combinator庫:

object ParserCombinator extends App with JavaTokenParsers with PackratParsers {

  case class Attr(value:String)
  case class Fig2d(name:String, attrs:List[Attr], children:List[Fig2d])

  def fig2d:Parser[Fig2d] = (ident <~ "{") ~ rep(attr) ~ (rep(fig2d) <~ "}") ^^ {
    case name ~ attrs ~ children => Fig2d(name, attrs, children)
  }

  def attr:Parser[Attr] = "attribute" ~> "=" ~> "\\S+".r ^^ Attr.apply

  def fig2dList = rep(fig2d)

  val input =
    """
      |rectangle1{
      |    attribute = foo
      |}
      |ellipse1{
      |    attribute = foo
      |    ellipse{
      |        rectangle{
      |            attribute = foo
      |        }
      |    }
      |}
    """.stripMargin


  println(parseAll(fig2dList, input))
}

打印:

 [13.5] parsed: List(Fig2d(rectangle1,List(Attr(foo)),List()), Fig2d(ellipse1,List(Attr(foo)),List(Fig2d(ellipse,List(),List(Fig2d(rectangle,List(Attr(foo)),List()))))))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM