Minimal, super readable string pattern matching for python.

Overview

logo

simplematch

Minimal, super readable string pattern matching for python.

PyPI Version PyPI - License tests

import simplematch

simplematch.match("He* {planet}!", "Hello World!")
>>> {"planet": "World"}

simplematch.match("It* {temp:float}°C *", "It's -10.2°C outside!")
>>> {"temp": -10.2}

Installation

pip install simplematch

(Or just drop the simplematch.py file in your project.)

Syntax

simplematch has only two syntax elements:

  • wildcard *
  • capture group {name}

Capture groups can be named ({name}), unnamed ({}) and typed ({name:float}).

The following types are available:

  • int
  • float
  • email
  • url
  • ipv4
  • ipv6
  • bitcoin
  • ssn (social security number)
  • ccard (matches Visa, MasterCard, American Express, Diners Club, Discover, JCB)

For now, only named capture groups can be typed.

Then use one of these functions:

import simplematch

simplematch.match(pattern, string) # -> returns a `dict` on match, `None` otherwise.
simplematch.test(pattern, string)  # -> returns `True` on match, `False` otherwise.

Or use a Matcher object:

import simplematch as sm

matcher = sm.Matcher(pattern)

matcher.match(string) # -> returns a dict or None
matcher.test(string)  # -> returns True / False
matcher.regex         # -> shows the generated regex

Basic usage

import simplematch as sm

# extracting data
sm.match(
    pattern="Invoice_*_{year}_{month}_{day}.pdf",
    string="Invoice_RE2321_2021_01_15.pdf")
>>> {"year": "2021", "month": "01", "day": "15"}

# test match only
sm.test("ABC-{value:int}", "ABC-13")
>>> True

Typed matches

import simplematch as sm

matcher = sm.Matcher("{year:int}-{month:int}: {value:float}")

# extracting data
matcher.match("2021-01: -12.786")
>>> {"year": 2021, "month": 1, "value": -12.786}

# month is no integer -> no match and return `None`.
matcher.match("2021-AB: Hello")
>>> None

# no extraction, only test for match
matcher.test("1234-01: 123.123")
>>> True

# show generated regular expression
matcher.regex
>>> '^(?P<year>[+-]?[0-9]+)\\-(?P<month>[+-]?[0-9]+):\\ (?P<value>[+-]?(?:[0-9]*[.])?[0-9]+)$'

# show registered converters
matcher.converters
>>> {'year': <class 'int'>, 'month': <class 'int'>, 'value': <class 'float'>}

Register your own types

You can register your own types to be available for the {name:type} matching syntax with the register_type function.

simplematch.register_type(name, regex, converter=str)

  • name is the name to use in the matching syntax
  • regex is a regular expression to match your type
  • converter is a callable to convert a match (str by default)

Example

Register a smiley type to detect smileys (:), :(, :/) and getting their moods:

import simplematch as sm

def mood_convert(smiley):
    moods = {
        ":)": "good",
        ":(": "bad",
        ":/": "sceptic",
    }
    return moods.get(smiley, "unknown")

sm.register_type("smiley", r":[\)\(\/]", mood_convert)

sm.match("I'm feeling {mood:smiley} *", "I'm feeling :) today!")
>>> {"mood": "good"}

Background

simplematch aims to fill a gap between parsing with str.split() and regular expressions. It should be as simple as possible, fast and stable.

The simplematch syntax is transpiled to regular expressions under the hood, so matching performance should be just as good.

I hope you get some good use out of this!

Contributions

Contributions are welcome! Just submit a PR and maybe get in touch with me via email before big changes.

License

MIT

Owner
Thomas Feldmann
Thomas Feldmann
A Blender addon for VSE that auto-adjusts video strip's length, if speed effect is applied.

Blender VSE Speed Adjust Addon When using Video Sequence Editor in Blender, the speed effect strip doesn't auto-adjusts clip length when changing its

Arpit Srivastava 2 Jan 18, 2022
Python implementation for Active Directory certificate abuse

Certipy is a Python tool to enumerate and abuse misconfigurations in Active Directory Certificate Services (AD CS). Based on the C# variant Ce

Oliver Lyak 1.3k Jan 09, 2023
Defichain maxi - Scripts to optimize performance on defichain rewards

defichain_maxi This script is made to optimize your defichain vault rewards by m

kuegi 75 Dec 31, 2022
Anonfiles files leaker via keyword.

Anonfiles files leaker via keyword

Trac3D1y 6 Nov 23, 2022
Tips that improve your life in one way or another

Tips that improve your life in one way or another. This software downloads life tips from reddit.com/r/LifeProTips and tweet the most upvoted tips on Twitter.

Burak Tokman 2 Aug 04, 2022
Med to csv - A simple way to parse MedAssociate output file in tidy data

MedAssociates to CSV file A simple way to parse MedAssociate output file in tidy

Jean-Emmanuel Longueville 5 Sep 09, 2022
LinuxHelper - A collection of utilities for non-technical Linux users accessible via a GUI

Linux Helper A collection of utilities for non-technical Linux users accessible via a GUI This app is still in very early development, expect bugs and

Seth 7 Oct 03, 2022
Pomodoro timer by the Algodrip team!

PomoDrip 🍅 Pomodoro timer by the Algo Drip team! To-do: Create the script for the pomodoro timer Design the front-end of the program (Flask or Javasc

Algodrip 3 Sep 12, 2021
A Notifier Program that Notifies you to relax your eyes Every 15 Minutes👀

Every 15 Minutes is an application that is used to Notify you to Relax your eyes Every 15 Minutes, This is fully made with Python and also with the us

Ashely Sato 1 Nov 02, 2021
Odoo modules related to website/webshop

Website Apps related to Odoo it's website/webshop features: webshop_public_prices: allow configuring to hide or show product prices and add to cart bu

Yenthe Van Ginneken 9 Nov 04, 2022
An example project which contains the Unity components necessary to complete Navigation2's SLAM tutorial with a Turtlebot3, using a custom Unity environment in place of Gazebo.

Navigation 2 SLAM Example This example provides a Unity Project and a colcon workspace that, when used together, allows a user to substitute Unity as

Unity Technologies 183 Jan 04, 2023
Reconhecimento de voz, em português, com python

Speech_recognizer Reconhecimento de voz, em português, com python O ato de falar nada mais é que criar vibrações no ar. Por meio de um conversor analó

Marcus Vinícius Ribeiro Andrade 1 Dec 14, 2021
Team Hash Brown Science4Cast Submission

Team Hash Brown Science4Cast Submission This code reproduces Team Hash Brown's (@princengoc, @Xieyangxinyu) best submission (ee5a) for the competition

3 Feb 02, 2022
Programa principal de la Silla C.D.P.

Silla CDP Página Web Contáctenos Lista de contenidos: Información del proyecto. Licencias. Contacto. Información del proyecto Silla CDP, o Silla Corre

Silla Control de Postura 1 Dec 02, 2021
Learning a Little about Containerlab

Learning a Little about Containerlab Hello all. This is the respository based on this blog post. Getting Started Feel free to use this example. You wi

10 Oct 16, 2022
Fonts used to be an install-and-forget thing, but many of are now updated regularly.

Your font manager. Fonts used to be an install-and-forget thing, but many of are now updated regularly. fontman helps you keep track of the fonts you

Nico Schlömer 20 Feb 07, 2022
Batch generate asset browser previews

When dealing with hundreds of library files it becomes tedious to mark their contents as assets. Using python to automate the process is a perfect fit

54 Dec 24, 2022
An Agora Python Flask token generation server

A Flask Starter Application with Login and Registration About A token generation Server using the factory pattern and Blueprints. A forked stripped do

Nii Ayi 1 Jan 21, 2022
A simple script for generating screenshots with Vapoursynth

Vapoursynth-Screenshots A simple script for generating screenshots with Vapoursynth. About I'm lazy, and hate changing variables for each batch of scr

7 Dec 31, 2022
It really seems like Trump is trying to get his own social media started. Not a huge fan tbh.

FuckTruthSocial It really seems like Trump is trying to get his own social media started. Not a huge fan tbh. (When TruthSocial actually releases, I'l

0 Jul 18, 2022