Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to match an exact string with hyperscan like with re.findall #39

Open
rafikg opened this issue Jun 9, 2022 · 0 comments
Open

How to match an exact string with hyperscan like with re.findall #39

rafikg opened this issue Jun 9, 2022 · 0 comments

Comments

@rafikg
Copy link

rafikg commented Jun 9, 2022

from typing import Optional, Any, List
import hyperscan


def on_match(id: int, start: int, end: int, flags: int, context: Optional[Any] = None) -> Optional[bool]:
    context['results'].append((id, start, end))
    return 0


db = hyperscan.Database()
patterns = (
    # expression,  id, flags
    (br'O+M',      0,  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
)
lines = ['Om', 'OOm', 'oom', 'sroom', 'communication', 'surveillance']

context = {'results': []}

text = str.encode("\n".join(lines))
print(text)

db.scan(text, match_event_handler=on_match, context=context)

for result in context['results']:
    print(result)

(0, 0, 2) ->Om
(0, 3, 6) -> OOm
(0, 7, 10) -> oom
(0, 13, 16) ->oom (in sroom)
(0, 18, 20)->om (in communication)

with re.findall()

re.findall(rb'O+M', text, flags=re.IGNORECASE)
[b'Om', b'OOm', b'oom', b'oom']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant