简体   繁体   English

使用正则表达式在SML中编写语法规则

[英]Writing grammar rules in SML Using Regular Expressions

I want to write a converter for iCalendar to CSV in SML. 我想在SML中将iCalendar转换为CSV。 Hence, I need to write grammar rules for it. 因此,我需要为此编写语法规则。 I understand that certain rules can be written by defining them as datatype . 我了解可以通过将某些规则定义为datatype来编写某些规则。 To begin with, I am facing problems to write rules for Regular Expressions (terminals). 首先,我面临编写正则表达式(终端)规则的问题。

As an example, I want to write the given Regex in SML : 例如,我想用SML编写给定的Regex:

label → [a-zA-Z0-9-]+ 标签→[a-zA-Z0-9-] +

Can anybody tell me how to write this rule in SML? 谁能告诉我如何用SML编写此规则?

EDIT 编辑

So far, I have declared a datatype variables that denotes the various variables of the grammar. 到目前为止,我已经声明了一个数据类型variables ,该变量表示语法的各种变量。

datatype variables = Label of String

I have declared a function isLabel . 我已经声明了一个函数isLabel It takes as input s (of type string ) and returns Label(s) if it satisfies the given regex (by checking if ASCII values lie in the given range) else raises exception. 如果它满足给定的正则表达式(通过检查ASCII值是否在给定的范围内),则将其作为输入s (类型为string )并返回Label(s) ,否则引发异常。 I gotta feeling that I have found the way to solve. 我感到我已经找到解决方法。

Other symbols/variables of the grammar can be defined similarly in the datatype variables. 可以在datatype variables.类似地定义语法的其他符号/ datatype variables.

See Unix Programming with Standard ML page 163+ for an example of SML/NJ's regular expression library in action. 有关正在使用的SML / NJ正则表达式库的示例,请参见《 使用标准ML进行Unix编程》(第163页)。

Steps: 脚步:

Add SML/NJ Library. 添加SML / NJ库。 In the smlnj REPL use: 在smlnj REPL中使用:

CM.make "$/regexp-lib.cm"

Make a regular expression Engine: 制作一个正则表达式引擎:

structure RE = RegExpFn (structure P = AwkSyntax
                         structure E = BackTrackEngine)

Define label : 定义label

val label = RE.compileString "[a-zA-Z0-9-]+"

Define a target: 定义目标:

val target = "ab9A-f"

Match label against target: 将标签与目标匹配:

val match = StringCvt.scanString (RE.find label) target

Extract values from match according to program logic. 根据程序逻辑从match提取值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM