簡體   English   中英

用於遞歸語法定義的Ruby正則表達式?

[英]Ruby regular expressions for recursive grammar definitions?

如何使用正則表達式來驗證遞歸語法定義? 例如,說我有以下語法:

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

這只是遞歸定義的意思的一個示例-我不是在尋找一個專門解決此問題的正則表達式,而是更多如何使用正則表達式解決此類問題。

這是匹配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>

暫無
暫無

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

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