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
Software that extracts spreadsheets from various .pdf files to .csv

Extração de planilhas de diversos arquivos .pdf para .csv O código inteiro foi desenvolvido em Python. Foi utilizado o pacote "tabula" e a biblioteca

Marcos Silva 2 Jan 09, 2022
Simple tools to make/dump CPC+ CPR cartridge files

Simple tools to make/dump CPC+ CPR cartridge files mkcpr.py: make a CPR file from files (one chunk per file); see notes cprdump.py: dump the chunks of

Juan J. Martínez 3 May 30, 2022
Zeus - Advanced Punishments with Embeds.

Zeus Advanced Punishments with Embeds. Make sure to put the Discord Bot Token in the " TOKEN = '' " Language Python Features Ban Kick Mute Unmute Warn

2 Jan 05, 2022
Reactjs web app written entirely in python, using transcrypt compiler.

Reactjs web app written entirely in python, using transcrypt compiler.

Dan Shai 22 Nov 27, 2022
emoji-math computes the given python expression and returns either the value or the nearest 5 emojis as measured by cosine similarity.

emoji-math computes the given python expression and returns either the value or the nearest 5 emojis as measured by cosine similarity.

Andrew White 13 Dec 11, 2022
A Lite Package focuses on making overwrite and mending functions easier and more flexible.

Overwrite Make Overwrite More flexible In Python A Lite Package focuses on making overwrite and mending functions easier and more flexible. Certain Me

2 Jun 15, 2022
Combines power of torch, numerical methods to conquer and solve ALL {O,P}DEs

torch_DE_solver Combines power of torch, numerical methods and math overall to conquer and solve ALL {O,P}DEs There are three examples to provide a li

Natural Systems Simulation Lab 28 Dec 12, 2022
Repo contains Python Code Reference to learn Python in a week, It also contains Machine Learning Algorithms and some examples for Practice, Also contains MySql, Tableau etc

DataScience_ML_and_Python Repo contains Python Code Reference to learn Python in a week, It also contains Machine Learning Algorithms and some example

Meerabo D Shah 1 Jan 17, 2022
Linux Security and Monitoring Scripts

Linux Security and Monitoring Scripts These are a collection of security and monitoring scripts you can use to monitor your Linux installation for sec

Andre Pawlowski 65 Aug 27, 2022
A simple chatbot that I made for school project

Chatbot: Python A simple chatbot that I made for school Project. Tho this chatbot is dumb sometimes, but it's not too bad lol. Check it Out! FAQ How t

Prashant 2 Nov 13, 2021
Files relating to polymtl university

This is a tool I developed quickly, which allows users to visualize class availability by day of the week for a given program at polymtl. The schedule

PN 3 Mar 15, 2022
🎉 🎉 PyComp - Java Code compiler written in python.

🎉 🎉 PyComp Java Code compiler written in python. This is yet another compiler meant for babcock students project which was created using pure python

Alumona Benaiah 5 Nov 30, 2022
Repo to demo translating colab/jupyter notebook to streamlit webapp

Repo to demo translating colab/jupyter notebook to streamlit webapp

Marisa Smith 2 Feb 02, 2022
IST-Website - IST Tutoring Portal for python

IST Tutoring Portal This portal is a web based interface to handle student help

Jean 3 Jan 03, 2022
Structured, dependable legos for starknet development.

Structured, dependable legos for starknet development.

Alucard 127 Nov 23, 2022
💘 Write any Python with 9 Characters: e,x,c,h,r,(,+,1,)

💘 PyFuck exchr(+1) PyFuck is a strange playful code. It uses only nine different characters to write Python3 code. Inspired by aemkei/jsfuck Example

Satoki 10 Dec 25, 2022
Group P-11's submission for the University of Waterloo's 2021 Engineering Competition (Programming section).

P-11-WEC2021 Group P-11's submission for the University of Waterloo's 2021 Engineering Competition (Programming section). Part I Compute typing time f

TRISTAN PARRY 1 May 14, 2022
Toppr Os Auto Class Joiner

Toppr Os Auto Class Joiner Toppr os is a irritating platform to work with especially for students it takes a while and is problematic most of the time

1 Dec 18, 2021
Binary++ is an esoteric programming language based on* binary

Binary++ is an esoteric programming language based on* binary. * It's meant to be based on binary, but you can write Binary++ code using different mea

Supercolbat 3 Feb 18, 2022
Simple Denial of Service Program yang di bikin menggunakan bahasa pemograman Python,

Peringatan Tujuan kami share code Indo-DoS hanya untuk bertujuan edukasi / pembelajaran! Dilarang memperjual belikan source ini / memperjual-belikan s

SonLyte 8 Nov 07, 2021