Regex scala正则表达式过滤器包元素
我有如下字符串形式的输入Regex scala正则表达式过滤器包元素,regex,scala,Regex,Scala,我有如下字符串形式的输入 ellipse { attribute = foo ellipse { attribute = foo line { attribute = foo attribute = foo attribute = foo } line { attribute = foo attr
ellipse {
attribute = foo
ellipse {
attribute = foo
line {
attribute = foo
attribute = foo
attribute = foo
}
line {
attribute = foo
attribute = foo
}
}
}
基本上,它是关于二维元素的,能够在其中容纳其他二维元素。我的任务是编写一个正则表达式,它可以将父元素与其子元素分开,这样就可以分别对它们进行解析。
在下列情况下:
rectangle1{
attribute = foo
}
ellipse1{
attribute = foo
ellipse{
rectangle{
attribute = foo
}
}
}
我希望能够regex.findAllIn(string)
,然后只有矩形1和椭圆1字符串,这样我就可以解析它们了。
我不是正则表达式专家,但我做了一次尝试,当然失败了:
我试图:
(?)(?!((椭圆|点|线)\\{)+(椭圆|点|线)\{.\\}
获取所有椭圆、点或线,这些
(?)(?!((椭圆|点|线)\\{)+(椭圆|点|线)\{.\\}
包括一些东西,但是
(?s)(?!((椭圆|点|线)\\{)+(椭圆|点|线)\{.\\}
不要
(?s)(?!((椭圆|点|线)\{))+(椭圆|点|线)\{.\\}
在它们上面有类似于椭圆{或点{的东西
但是这不起作用
很可能有一种方法可以满足我的需求,但正如我所说,我不是正则表达式专家。如果你能给我一个答案,我将非常感谢你的解释,因为我想了解解决方案。
提前感谢您!纯正则表达式不太适合此任务。您必须使用递归正则表达式,而Java(以及Scala)目前不支持它们 但是,在使用Scala时,您可以利用强大的库:
如果我正确理解您的任务,那么我认为正则表达式不是这里的正确工具。sooo..您会怎么做?对于字符串拆分操作,我仍然需要正则表达式,对吗?如果您使用scala,我建议您使用此任务。(。谢谢,您能解释一下(ident[…])是什么吗在你的程序的第6行中有吗?我有一个想法,但在你提到的教程中我发现这样没有用。@Julian,它是在
JavaTokenParsers
中定义的:“任何有效的Java标识符,根据”。我用它来匹配2d元素的名称。显然,你可以用正则表达式解析器或任何你喜欢的东西来替换它。或者你是说整行?
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()))))))