• Stars
    star
    172
  • Rank 221,201 (Top 5 %)
  • Language
    Rust
  • License
    MIT License
  • Created about 5 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

lazy static regular expressions checked at compile time

MIT Latest Version docs Chat on Miaou

lazy-regex

With lazy-regex macros, regular expressions

  • are checked at compile time, with clear error messages
  • are wrapped in once_cell lazy static initializers so that they're compiled only once
  • can hold flags as suffix: let case_insensitive_regex = regex!("ab*"i);
  • are defined in a less verbose way

The regex! macro returns references to normal instances of regex::Regex or regex::bytes::Regex so all the usual features are available.

Other macros are specialized for testing a match, replacing with concise closures, or capturing groups as substrings in some common situations:

  • regex_is_match!
  • regex_find!
  • regex_captures!
  • regex_replace!
  • regex_replace_all!

All of them support the B flag for the regex::bytes::Regex variant.

Some structs of the regex crate are reexported to ease dependency managment. The regex crate itself is also reexported, to avoid the need to synchronize the versions/flavor (see Features below)

Build Regexes

use lazy_regex::regex;

// build a simple regex
let r = regex!("sa+$");
assert_eq!(r.is_match("Saa"), false);

// build a regex with flag(s)
let r = regex!("sa+$"i);
assert_eq!(r.is_match("Saa"), true);

// you can use a raw literal
let r = regex!(r#"^"+$"#);
assert_eq!(r.is_match("\"\""), true);

// or a raw literal with flag(s)
let r = regex!(r#"^\s*("[a-t]*"\s*)+$"#i);
assert_eq!(r.is_match(r#" "Aristote" "Platon" "#), true);

// build a regex that operates on &[u8]
let r = regex!("(byte)?string$"B);
assert_eq!(r.is_match(b"bytestring"), true);

// there's no problem using the multiline definition syntax
let r = regex!(r#"(?x)
    (?P<name>\w+)
    -
    (?P<version>[0-9.]+)
"#);
assert_eq!(r.find("This is lazy_regex-2.2!").unwrap().as_str(), "lazy_regex-2.2");
// (look at the regex_captures! macro to easily extract the groups)
// this line doesn't compile because the regex is invalid:
let r = regex!("(unclosed");

Supported regex flags: i, m, s, x, U.

See regex::RegexBuilder.

Test a match

use lazy_regex::regex_is_match;

let b = regex_is_match!("[ab]+", "car");
assert_eq!(b, true);

Extract a value

use lazy_regex::regex_find;

let f_word = regex_find!(r#"\bf\w+\b"#, "The fox jumps.");
assert_eq!(f_word, Some("fox"));
let f_word = regex_find!(r#"\bf\w+\b"#B, b"The forest is silent.");
assert_eq!(f_word, Some(b"forest" as &[u8]));

Capture

use lazy_regex::regex_captures;

let (_, letter) = regex_captures!("([a-z])[0-9]+"i, "form A42").unwrap();
assert_eq!(letter, "A");

let (whole, name, version) = regex_captures!(
    r#"(\w+)-([0-9.]+)"#, // a literal regex
    "This is lazy_regex-2.0!", // any expression
).unwrap();
assert_eq!(whole, "lazy_regex-2.0");
assert_eq!(name, "lazy_regex");
assert_eq!(version, "2.0");

There's no limit to the size of the tuple. It's checked at compile time to ensure you have the right number of capturing groups.

You receive "" for optional groups with no value.

Replace with captured groups

The [regex_replace!] and [regex_replace_all!] macros bring once compilation and compilation time checks to the replace and replace_all functions.

Replacing with a closure

use lazy_regex::regex_replace_all;

let text = "Foo8 fuu3";
let text = regex_replace_all!(
    r#"\bf(\w+)(\d)"#i,
    text,
    |_, name, digit| format!("F<{}>{}", name, digit),
);
assert_eq!(text, "F<oo>8 F<uu>3");

The number of arguments given to the closure is checked at compilation time to match the number of groups in the regular expression.

If it doesn't match you get, at compilation time, a clear error message.

Replacing with another kind of Replacer

use lazy_regex::regex_replace_all;
let text = "UwU";
let output = regex_replace_all!("U", text, "O");
assert_eq!(&output, "OwO");

Shared lazy static

When a regular expression is used in several functions, you sometimes don't want to repeat it but have a shared static instance.

The regex! macro, while being backed by a lazy static regex, returns a reference.

If you want to have a shared lazy static regex, use the lazy_regex! macro:

use lazy_regex::*;

pub static GLOBAL_REX: Lazy<Regex> = lazy_regex!("^ab+$"i);

Like for the other macros, the regex is static, checked at compile time, and lazily built at first use.

Features and reexport

With default features, lazy-regex use the regex crate with its default features, tailored for performances and complete Unicode support.

You may enable a different set of regex features by directly enabling them when importing lazy-regex.

It's also possible to use the regex-lite crate instead of the regex crate by declaring the lite feature:

lazy-regex = { version = "2.6.0", default-features = false, features = ["lite"] }

The lite flavor comes with slightly lower performances and a reduced Unicode support (see crate documentation) but also a much smaller binary size.

If you need to refer to the regex crate in your code, prefer to use the reexport (i.e. use lazy_regex::regex;) so that you don't have a version or flavor conflict. When the lite feature is enabled, lazy_regex::regex refers to regex_lite so you don't have to change your code when switching regex engine.

More Repositories

1

broot

A new way to see and navigate directory trees : https://dystroy.org/broot
Rust
9,958
star
2

bacon

background rust code check
Rust
1,399
star
3

termimad

A library to display rich (Markdown) snippets and texts in a rust terminal application
Rust
834
star
4

rhit

A nginx log explorer
Rust
806
star
5

dysk

A linux utility to get information on filesystems, like df but better
Rust
780
star
6

miaou

A chat server with OAuth2 authentication, persistent and searchable history, video and audio, markdown formatting, private and public rooms, stars, votes, embedded games, and many other features
JavaScript
536
star
7

JSON.prune

A pruning version of JSON.stringify, allowing for example to stringify window or any big or recursive object
JavaScript
159
star
8

backdown

A deduplicator
Rust
94
star
9

safecloset

Cross-platform Secure TUI Secret Locker
Rust
81
star
10

hu.js

A very light JavaScript library for SVG
JavaScript
71
star
11

resc

A task orchestrator using redis, written in rust
Rust
63
star
12

clap-help

A more compact help renderer for clap terminal applications
Rust
56
star
13

whalespotter

Find those big fat files and folders
Rust
53
star
14

lapin

A game I built under direction of my kids
Rust
49
star
15

codesort

codesort sorts code
Rust
43
star
16

glassbench

A micro-benchmark framework to use with cargo bench
Rust
40
star
17

mazter

Mazes in your terminal
Rust
35
star
18

bet

Build and evaluate binary expression trees
Rust
33
star
19

tzdetect.js

A JavaScript library to detect the timezone using Moment.js
JavaScript
31
star
20

clima

A minimal viewer for Termimad
Rust
30
star
21

nvim-bacon

bacon's companion for neovim
Lua
29
star
22

deser-hjson

A Serde 1.0 compatible Rust deserializer for Hjson
Rust
27
star
23

minimad

Rust Markdown Parser
Rust
23
star
24

crokey

Rust
22
star
25

snow

Make it snow on your web site
JavaScript
21
star
26

coolor

tiny color conversion library for TUI application builders
Rust
17
star
27

wasm-tictactoe

Example of a 100% pure Rust, framework free, wasm application
Rust
15
star
28

lfs-core

rust crate to get information on mounted disks on linux
Rust
15
star
29

splitty

A Rust string splitter taking quotes into account
Rust
15
star
30

fediback

A Mastodon account backuper
Rust
14
star
31

Chrall

Extension Chrome pour Mounty Hall
JavaScript
14
star
32

print_key

an utility printing the key combinations you try on your terminal
Rust
14
star
33

JSON.parseMore

A not eval based JSON parser handling NaN and infinities
JavaScript
12
star
34

csv2svg

Rust
12
star
35

starry

A tool to collect github stars counts
Rust
12
star
36

terminal-light

Tells you whether the terminal is "dark" or "light"
Rust
11
star
37

patine

A minimalist color scheme for vim
Vim Script
11
star
38

SpaceBullet

JavaScript
11
star
39

terminal-clipboard

A cross-platform text only clipboard facade for terminal applications written in Rust
Rust
10
star
40

umask

A utility to deal with unix access permission modes
Rust
9
star
41

bounded-cache

A fast in memory cache forgetting the least recently accessed entry when the maximal number of entries is reached.
JavaScript
8
star
42

dys-config

Personal configuration files, for easier sharing between all my computers
Vim Script
7
star
43

squale

Small utility to scale images
Rust
6
star
44

miaou.gpt

A chat bot for Miaou, using the OpenAPI API
JavaScript
6
star
45

cli-log

a simple file logging facility, convenient for Rust terminal applications
Rust
5
star
46

skillrep

A small experiment at recomputing Stack Exchange reputation for evaluating skills
Go
5
star
47

braldop

Extensions du jeu Braldahim
JavaScript
5
star
48

keybindings-example

Rust
4
star
49

locmess

draws an histogram of the lengths of your LOC
Rust
4
star
50

bench-config-deserializers

A benchmark of Rust/serde deserializers on configuration files
Rust
4
star
51

anolog

access log anonymizer
Rust
3
star
52

termux-clipboard

Rust
3
star
53

yaml-patcher

An utility to change values in YAML files
Rust
3
star
54

char_reader

A buffered char reader for rust, not breaking on wild contents
Rust
3
star
55

kidding

Rust
2
star
56

strict

Rust
2
star
57

jacquerie

Similar to jQuery but without the burden of history
JavaScript
2
star
58

weblowercaser

A small program to change all file names and internal links in lowercase
Go
2
star
59

dom-doll

A nano Javascript lib to enchant the HTML DOM
JavaScript
2
star
60

mastodys-settings

stylesheet of the mastodon.dystroy.org Mastodon instance
CSS
2
star
61

secular

no diacr!
Rust
2
star
62

miaou.flying-toasters

No description or website provided
JavaScript
2
star
63

Canop

2
star
64

file-archive

A simple archiver storing files in a date based tree
JavaScript
1
star
65

dysp

Rust
1
star
66

albumin

Simple Hierarchical Album Generator
JavaScript
1
star
67

proc-status

a crate giving you information about a process, for example yours
Rust
1
star
68

groumf

Fast search and replace on strings or dom elements
JavaScript
1
star
69

domus

A DOM library that I hope to be able to forget soon enough (don't use it)
Rust
1
star
70

war-js

A repo for the SO JS ROOM GAME COMPETITION , and remake of Scratch W.A.R.
JavaScript
1
star
71

miaou.mountyhall

A plugin for miaou, dedicated to the MountyHall game
JavaScript
1
star
72

xterm-query

utility to query the terminal
Rust
1
star
73

byo-graphql

A simple "bring your own types and queries" GraphQL client
Rust
1
star
74

prompter

bash prompt designer
HTML
1
star
75

file-size

just a Rust function formatting file sizes in 4 chars
Rust
1
star
76

miaou.fireworks

A command to launch Fireworks in Miaou chat rooms
JavaScript
1
star
77

taliner.js

Is the caret on the first line of the textarea ? On the last line ?
HTML
1
star
78

canop.github.com

1
star
79

walk_pace

A simple evaluation of the cost of using rust's standard WalkDir
Rust
1
star