niro/hoa-regex

Hoa\Regex 库。

1.17.01.14 2022-03-31 17:17 UTC

README

Hoa

Build status Code coverage Packagist License

Hoa 是一套 模块化可扩展结构化 的 PHP 库。
此外,Hoa 致力于成为工业和研究世界之间的桥梁。

Hoa\Regex

Help on IRC Help on Gitter Documentation Board

此库提供分析正则表达式并基于正则表达式生成字符串的工具(Perl 兼容正则表达式)。

了解更多.

安装

使用 Composer,要将此库包含到依赖中,您需要添加 hoa/regex

$ composer require niro/hoa-regex '~1.0'

有关更多安装步骤,请参阅 源码页面

测试

在运行测试套件之前,必须安装开发依赖

$ composer install

然后,运行所有测试套件

$ vendor/bin/hoa test:run

有关更多信息,请参阅 贡献指南

快速使用

为了快速了解,我们建议查看两个示例。首先,分析一个正则表达式,即进行词法分析、解析并生成 AST。其次,通过以各向同性随机方法遍历其 AST,基于正则表达式生成字符串。

分析正则表达式

我们需要 Hoa\Compiler 来对以下正则表达式进行词法分析、解析并生成 AST:ab(c|d){2,4}e?。因此

// 1. Read the grammar.
$grammar  = new Hoa\File\Read('hoa://Library/Regex/Grammar.pp');

// 2. Load the compiler.
$compiler = Hoa\Compiler\Llk\Llk::load($grammar);

// 3. Lex, parse and produce the AST.
$ast      = $compiler->parse('ab(c|d){2,4}e?');

// 4. Dump the result.
$dump     = new Hoa\Compiler\Visitor\Dump();
echo $dump->visit($ast);

/**
 * Will output:
 *     >  #expression
 *     >  >  #concatenation
 *     >  >  >  token(literal, a)
 *     >  >  >  token(literal, b)
 *     >  >  >  #quantification
 *     >  >  >  >  #alternation
 *     >  >  >  >  >  token(literal, c)
 *     >  >  >  >  >  token(literal, d)
 *     >  >  >  >  token(n_to_m, {2,4})
 *     >  >  >  #quantification
 *     >  >  >  >  token(literal, e)
 *     >  >  >  >  token(zero_or_one, ?)
 */

我们了解到整个表达式由两个标记的单个连接组成:ab,然后是一个量词,然后是另一个量词。第一个量词是一个选择(在两个标记之间选择)的组合:cd,2 到 4 次。第二个量词是 e 标记,可以出现 0 或 1 次。

我们可以使用 Hoa\Visitor 来遍历树。

基于正则表达式生成字符串

要基于正则表达式的 AST 生成字符串,我们将使用 Hoa\Regex\Visitor\Isotropic 访问者

$generator = new Hoa\Regex\Visitor\Isotropic(new Hoa\Math\Sampler\Random());
echo $generator->visit($ast);

/**
 * Could output:
 *     abdcde
 */

生成的字符串是随机的,并且与给定的正则表达式匹配。

文档

Hoa\Regex 的黑客手册 包含有关如何使用此库及其工作方式的详细信息。

要本地生成文档,请执行以下命令

$ composer require --dev hoa/devtools
$ vendor/bin/hoa devtools:documentation --open

更多文档可以在项目的网站上找到: hoa-project.net

获取帮助

主要有两种方式可以获得帮助

贡献

你想贡献吗?谢谢!详细的 贡献指南 解释了你需要了解的一切。

许可

Hoa 采用新 BSD 许可证(BSD-3-Clause)。有关详细信息,请参阅 LICENSE