2016-11-14 128 views
0

我需要将以下EBNF转换为与任何有效格式字符串匹配的正则表达式。例如, '< 8', '*^10', '+ 6', '15,0.2' 等将EBNF转换为正则表达式

<spec> -> :[[<fill>]<align>][<sign>][<width>][,][.<prec>] 
<fill> -> <character> (* i.e., any one character) 
<align> -> < | > | = |^
<sign> -> + | - | ' ' 
<width> -> <integer> (* i.e, one or more digits 0....9 *) 
<prec> -> <integer> 
+0

向我们展示你尝试过什么 – nozzleman

回答

0

如果正则表达式引擎支持命名捕获组(FE PCRE),那么这可以工作:

^((?<fill>.?)(?<align>[<>=^]))?(?<sign>[ +\-]?)(?<width>[0-9]+)[,]?(?:[.](?<prec>[0-9]+))?$ 

测试here

注意,大多数是可选的,除了 “宽度” 捕获组。这是基于所有示例中都存在“宽度”的假设。

使用未命名捕获组,正则表达式变短:

^((.?)([<>=^]))?([ +\-]?)([0-9]+)[,]?(?:[.]([0-9]+))?$ 
相关问题