iak/regexbuilder

A fluent api that simplifies writing regular expressions

v1.0 2017-10-24 17:13 UTC

This package is auto-updated.

Last update: 2024-11-09 06:32:27 UTC


README

A fluent api that simplifies writing regular expressions. (for the ones of us who always forget the syntax)

Installation

Grab it using composer

$ composer require iak/regexbuilder
{
    "require": {
        "iak/regexbuilder": "^1.0"
    }
}

Simple as that :)

Introduction

This library is for all of us that find regular expressions hard to write and impossible to remember all the different flags, look aheads, capture groups etc.

Instead of spending that half hour searching stackoverflow, I hope you can easily whip up a pattern using this lib.

Note. a basic understading of how regular expressions is still needed.

Quick start

First of all, use the class at the top of you file,

use RegexBuilder\Regex;

Now you can use it like this

$string = "wow! this is cool!"

$match = Regex::word("wow")->symbol("!")->match($string); // wow!

Or maybe something more advanced (and demostrating some different ways of using the library)

    // Match an email address

    $email = "info@isakberglind.se";

    Regex::group("a-z0-9_-.")
        ->oneOrMore()
        ->symbol("@")
        ->group("a-z0-9_-].")
        ->oneOrMore()
        ->symbol(".")
        ->group("a-z")
        ->count(2,6)
        ->match($email);

    // a simple url-matcher

    $url = "http://www.landslide-design.se";

    Regex::word(["http", "https", "ftp"])
        ->symbols("://")
        ->capture(function ($query) {
            return $query->symbols("www.");
        })
        ->optional()
        ->group("a-zA-Z0-9@:._")
        ->count(2, 255)
        ->symbols(".")
        ->group(function ($query) {
            return $query->range("a", "z");
        })
        ->count(2, 6)
        ->group(function ($query) {
            return $query
                ->range("a", "z")
                ->range("A", "Z")
                ->range(0, 9)
                ->symbols("@:_.?//");
        })
        ->zeroOrMore()
        ->match($url);

Documentation

Words, patterns and symbols


word(mixed $word = null)

Matches provided word, array of words or any word

    $string = "This is a hard example!";

    Regex::word("simple")->replace("simple", $string);   // This is a simple example

    Regex::word(["This", "simple", "example"])->matchAll($string); // ["this", "example"]

    Regex::word()->matchAll($string) // ["this", "is", "a", "hard", "example"]

notWord()

Matches anything but a word

    $string = "Hi!!!!! What's up?";

    Regex::notWord()->match($string); // '!!!! '

symbols(string $symbols)

Matches provided symbols (escapes string, if you don't want that, use "pattern")

    $string = "This is &!^@? awesome!"

    Regex::symbols("&!^@?")->replace("totally", $string) // This is totally awesome

pattern(string $pattern)

Matches provided pattern
Aliases: raw()

    $string = "kickass example text";

    Regex::pattern("(example|text)")->matchAll($string); // ["example", "text"]

Characters


You can match a bunch of characters using the following helper methods

    Regex::digit();
    Regex::notDigit();
    Regex::whitespace();
    Regex::notWhitespace();
    Regex::char();
    Regex::notChar();
    Regex::hexDigit();
    Regex::octalDigit();
    Regex::newLine();
    Regex::carriageReturn();
    Regex::tab();
    Regex::verticalTab();
    Regex::formFeed();
    Regex::space();
    Regex::any();

Quantifiers


oneOrMore()

Matches one or more of preceding group, character or character set.

    $string = "Here are some numbers 123456. Cool huh?"

    Regex::digit()->oneOrMore()->match($string) // 123456

zeroOrMore()

Matches zero or more

    $string = "AA A1A A12A";

    Regex::char()->digit()->zeroOrMore()->char()->matchAll($string) // ["AA", "A1A", "A12A"]

count(int $count/$start, int $end = null)

Matches the specified amount or the minimum and maximun count

    $string = "1 12 123 1234";

    // Specify the exact count to match..
    Regex::digit()->count(3)->match($string); // 123

    // Or a minimum and maximum..
    Regex::digit()->count(2,4)->matchAll($string); // [12, 123, 1234]

Groups & Character sets


range(mixed $start, $mixed $end)

Specifies a range, made especially for working with character sets

    Regex::range("a", "z"); // a-z

group(mixed $pattern/$callback)

Creates a character set

    // Using a callback

    Regex::group(function ($builder) {
        return $builder->range("a", "z");
    });

    // Using a raw pattern

    Regex::group("a-z");

    // Produces the same;  [a-z]

Capture groups


capture(callable $callback = null)

Creates a capture group

    $string = "Capture this if you can!";

    // you can either capture the previous statement..

    Regex::word("this")->capture();

    // .. or using a callback

    Regex::capture(function ($builder) {
        return $builder->word("this");
    });

    // Produces the same; (this)

opionalCapture(mixed $pattern/$callback)

Creates a non capturing group

    $string = "Do not capture this if you can!";

    // you can either capture the previous statement..

    Regex::word("this")->capture();

    // .. or using a callback

    Regex::capture(function ($builder) {
        return $builder->word("this");
    });

    // Produces the same; (?:this)?

startCapture() and endCapture()

You can also surround what you want to capture with these methods

    $string = "Capture this if you can";

    Regex::startCapture()->word("this")->endCapture(); // (this)

Look aheads & look behinds


behind(mixed $pattern/$callback)

Creates a look behind
Aliases: beginsWith(), before()

    $string = "important";

    // Using a callback..
    Regex::behind(function ($builder) {
        return $builder->symbols("");
    })
    ->word()
    ->match($string);

    // .. or a raw pattern..
    Regex::behind("\*\*\*\*")->word()->match($string);

    // important

after(mixed $pattern/$callback)

Creates a look ahead, works exactly like before()
Aliases: endsWith()


Other helpers


optional(mixed $characters/$start = null, $length = null)

Makes capture group, character set or character optional

    $string = "Is it spelled color or colour?";

    // Using a characters
    Regex::word("colour")->optional("u")->matchAll($string); // ["color", "colour"]

    // Using a start and a length
    Regex::word("colour")->optional(4,1)->matchAll($string); // ["color", "colour"]

    // Make last statement optinal

    Regex::symbols("colo")->char("u")->optional()->symbols("r")->matchAll($string); // ["color", "colour"]

escape(string $pattern)

Escapes provided pattern

    $pattern = "^[]$<";

    Regex::escape($pattern); // \^\[\]\$\<

getPattern()

Returs the built up pattern

    Regex::group("a-zA-Z")->oneOrMore()->symbols("!!")->optional()->zeroOrMore()->getPattern(); // /[a-zA-Z]+!!?*/

release()

Removes built up pattern

    Regex::group("a-z")->symbol("!")->release()->symbols("only this")->getPattern(); // /only this/

Matching and replacing


replace($string, $subject)

Replace built up pattern with provided string

    $string = "This is a hashtag: @. I'm sure!";

    Regex::symbol("@")->replace("#", $string); // This is a hashtag: #. I'm sure!

match($string)

Matches the first occurrence of the built up pattern
Note! only return the match. If you want all capture groups, use matchWithGroups()

    $string = "Follow me on twitter: @Isak_Berglind!";

    Regex::symbol("@")->group("a-zA-Z_")->oneOrMore()->match($string); // @Isak_Berglind

matchAll($string)

Matches all of the occurences of the built up pattern
Note! only return the match. If you want all capture groups, use matchAllWithGroups()

    $string = "this is as good as it gets";

    Regex::any()->symbol("s")->matchAll($string); // ["is", "is", "as", "as", "ts"]