2013-10-14 38 views
0

如何使用正则表达式来验证递归语法定义?例如,假设我有以下的语法:用于递归语法定义的Ruby正则表达式?

 
    alpha := <beta> gamma | <alpha> <beta> 
    beta := delta epsilon 

这只是我的意思通过递归定义一个例子 - 我不是在寻找一个专门解决这个问题的正则表达式,但更多的如何处理类似正则表达式的问题。

+0

您的语法似乎只产生无限的词:-) – Bergi

+0

正则表达式produc只有普通的语言,而不是任意递归的语言 - 这可能是不可能的。检查http://www.regular-expressions.info/recurse.html是否支持递归。 – Bergi

+0

@Bergi我认为我现在修好了,但仔细检查(我不擅长现场提出这些问题)。 – Kvass

回答

1

这里有一个方法来匹配的Ruby 1.9递归模式,在这种情况下,嵌套括号的任意级别:

#!/usr/bin/env ruby 

text = "... { a { b { c } b } a { d } a } ..."; 
match = text.match(/(?<entire>\{(?:[^{}]+|\g<entire>)*\})/).captures 
puts match 

,它将打印:

{ a { b { c } b } a { d } a } 

快速突破的下降模式:

(?<entire>  # start named capture group called <entire> 
    \{    # match the literal '{' 
    (?:    # start non capture group 1 
    [^{}]+  #  match one or more chars other than '{' and '}' 
    |    #  OR 
    \g<entire> #  recursively match named group <entire> 
)*    # end non capture group 1 and repeat it zero or more times 
    \}    # match the literal '}' 
)     # end named capture group called <entire>