python使用hyperscan进行正则匹配性能提升demo

本文档详细介绍了Hyperscan的安装过程,包括依赖库的安装,如CMake、Ragel和Boost等。同时,提供了Python环境下安装hyperscan的两种方法:pip安装和源码安装,并给出了详细的使用示例,包括如何创建数据库、处理匹配事件及不同扫描模式的应用。此外,还分享了一个完整的Python Demo代码,帮助读者快速上手Hyperscan在Python中的应用。
摘要由CSDN通过智能技术生成

目录

hyperscan安装:

其他依赖:

安装详情过程:

Hyperscan for python安装:

python hyperscan使用:

完整Demo代码:


hyperscan安装:

hyperscan官方 Home Page - Hyperscan.io

hyperscan Github https://github.com/intel/hyperscan

hyperscan Source代码 Downloads - Hyperscan.io 或者可以去Github-Release里面去下载也可以

其他依赖:

CMake CMake

Ragel Ragel State Machine Compiler

Python Welcome to Python.org Python一般默认Linux安装

Boots Boost C++ Libraries

Pcap TCPDUMP/LIBPCAP public repository 可不用安装,仅测试的时候会用到。

安装详情过程:

本来想详细写一下安装过程,但是看到有作者写过了,写的也非常详细,此处不再重复写。

文档:Getting Started — Hyperscan 5.4.0 documentation

看不太懂的可以看这个 CSDN: Hyperscan 安装_耿小渣的进阶之路-CSDN博客_hyperscan安装

Hyperscan for python安装:

pip安装

pip install hyperscan

源码安装。Poetry Poetry - Python dependency management and packaging made easy

$ pip install poetry
$ git clone https://github.com/darvid/python-hyperscan.git
$ cd python-hyperscan
$ poetry install

如果可以 import hyperscan 即安装成功。

以上两个安装也可参考官方的QuickStart Hyperscan for Python

python hyperscan使用:

可以参考官方Usage Usage - Hyperscan for Python

通常我们需要先创建db-obj即Building a database

import hyperscan

db = hyperscan.Database()
patterns = (
    # expression,  id, flags
    (br'fo+',      0,  0),
    (br'^foobar$', 1,  hyperscan.HS_FLAG_CASELESS),
    (br'BAR',      2,  hyperscan.HS_FLAG_CASELESS
                       | hyperscan.HS_FLAG_SOM_LEFTMOST),
)
expressions, ids, flags = zip(*patterns)
db.compile(
    expressions=expressions, ids=ids, elements=len(patterns), flags=flags
)
print(db.info().decode())
# Version: 5.1.1 Features: AVX2 Mode: BLOCK

然后Handling - Template

# Type annotated Hyperscan match handler signature
def on_match(
    id: int,
    from: int,
    to: int,
    flags: int,
    context: Optional[Any] = None
) -> Optional[bool]:
    ...

Handling - Example (BlockMode)

def hyperscan_match(lines: List[str]) -> List[str]:
    result = []
    def on_match(id: int, froms: int, to: int, flags: int, context: Optional[Any] = None) -> Optional[bool]:
        result.append(TAG_LOOKUP[id])

    for line in lines:
        db.scan(line.encode("utf-8"), match_event_handler=on_match)

    return result

然后选择合适的Mode进行scan

Mode请参考上方的官方Usage

完整Demo代码:

不再重复写到blog,前去 https://blog.gcoperation.top/posts/da2ec18d/ 查看。

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值