silentbyte/sb-dynlex

一个具有流畅API的动态可配置词法分析器库。

1.1.0 2016-12-12 12:23 UTC

This package is auto-updated.

Last update: 2024-09-10 13:30:17 UTC


README

Build Status Latest Stable Version MIT License

这是SilentByte DynLex词法分析器库的主仓库。

DynLex是一个易于使用的PHP库,提供通过流畅界面创建和使用动态可配置词法分析器的功能。

官方文档可以在这里找到: http://docs.silentbyte.com/dynlex

安装

要安装最新版本,可以直接检出并包含源代码,或者使用

$ composer require silentbyte/sb-dynlex

通用用法

DynLex允许定义一组词法分析规则,这些规则确定如何扫描输入以及可以创建哪些标记。以下代码是一个简单的示例,它将单词和数字标记化

<?php

use SilentByte\DynLex\DynLexUtils;
use SilentByte\DynLex\DynLexBuilder;

$input = "Hello world 8273 this 919 28 is a 12 39 44 string"
    . "consisting of 328 words 003 and numbers 283";

$lexer = (new DynLexBuilder())
    ->rule('[a-zA-z]+', 'word')
    ->rule('[0-9]+',    'number')
    ->skip('.')
    ->build();

$tokens = $lexer->collect($input);
DynLexUtils::dumpTokens($tokens);

// [Output]
// -------------------------------------
// tag            off    ln   col  value
// -------------------------------------
// word             0     1     1  Hello
// word             6     1     7  world
// number          12     1    13  8273
// word            17     1    18  this
// number          22     1    23  919
// ...

?>

DynLex还允许指定在输入流中匹配相关标记时将执行的动作。扩展前面的示例,我们可以实现一个程序来计算输入流中单词和数字的数量

<?php

use SilentByte\DynLex\DynLexUtils;
use SilentByte\DynLex\DynLexBuilder;

$words = 0;
$numbers = 0;

$input = "hello world 8273 this 919 28 is a 12 39 44 string"
    . "consisting of 328 words 003 and numbers 283";

$lexer = (new DynLexBuilder())
    ->rule('[a-z]+', 'word',   function() use (&$words)   { $words++; })
    ->rule('[0-9]+', 'number', function() use (&$numbers) { $numbers++; })
    ->skip('.')
    ->build();

$tokens = $lexer->collect($input);
DynLexUtils::dumpTokens($tokens);

echo "$words words found.\n";
echo "$numbers numbers found.\n";

// [Output]
// -------------------------------------
// tag            off    ln   col  value
// -------------------------------------
// word             0     1     1  hello
// word             6     1     7  world
// number          12     1    13  8273
// word            17     1    18  this
// number          22     1    23  919
// ...
// -------------------------------------
// 11 words found.
// 9 numbers found.

?>

使用这个概念,可以轻松地为不同类型的应用程序创建词法分析器。一个更详细的示例,展示了如何使用DynLex创建编程语言的HTML语法高亮器,可以在examples/04-syntax-highlighting.php下找到。

通常建议检查examples文件夹以获取有关如何使用DynLex的更多信息示例。还可以查看源代码以获取更详细的文档。

贡献

请参阅CONTRIBUTING.md

常见问题解答

DynLex在什么许可证下发布?

MIT许可证。请查看license.txt以获取详细信息。有关MIT许可证的更多信息可以在这里找到:https://open-source.org.cn/licenses/MIT

为什么规则有时不能正确匹配?

您必须确保可能相互冲突的规则按从最具体到最一般的顺序列出。例如,如果您想标记整数([0-9]+)和小数([0-9]+\.[0-9]+),则小数的规则必须在小数的规则之前列出,因为整数规则匹配小数规则的第一部分。