Table Of Contents
- What's a pattern?
- Escaping
- Positional anchors
- Character classes
- Sets (character ranges)
- Quantifiers
- Capture groups
- Examples
- Testing
A pattern is describes the structure of a string you want to match. They are smilar, but not identitical to regular expressions.
To match one of the magic characters . ^ $ ( ) % [ ] * + - ?
, it must be escaped by prefixing with %
. For example, %%
will match "%".
Attach the pattern to the ^
beginning or $
end o of the string.
These match any character within their class.
Class | Represents | Inverse* |
---|---|---|
. |
Any character | |
%w |
Alphanumerics (from A to Z, a to z, and from 0 to 9) | %W |
%a |
Letters (A to Z and a to z) | %A |
%l |
Lowercase letters (a to z) | %L |
%u |
Uppercase letters (A to Z) | %U |
%d |
Digits (from 0 to 9) | %D |
%p |
Punctuation | %P |
%s |
Whitespace (" ", tab, line breaks) | %S |
* The inverse matches any character not in the class. For example, %D
matches anything that is not a digit.
Brackets allow you to create a custom character range or set. Examples:
Example | Meaning |
---|---|
[ab] |
"a" OR "b" |
[^ab] |
Anything but "a" or "b" |
[a-i] |
Between "a" and "i" in the alphabet |
[6-8] |
Between "6" and "8" |
[a-zA-Z0-9] |
Between "a" and "z" or between "A" and "Z" or between "0" and "9" (the same as %w ) |
To match [
or ]
literally, prefix it with %
.
Specify repetion by placing after any character, class, or range.
Quantifier | Matches previous item... |
---|---|
? |
0 or 1 times |
* |
0 to n (infinite) times |
+ |
1 to n times |
- |
0 or n times, ungreedy (matches shortest possible sequence) |
Without capture groups, the whole matching subject string is returned. Sometimes only certain parts are required.
Capture groups defines what to return. Multiple capture groups, multiple values are returned.
To make a capture group, enclose what you want to return with parentheses.
If you want to match the (
or )
char literally, put a "%" before it.
Match a string that...
- contains "apples" anywhere in it :
apples
- contains "apples" at the start of the string :
^apples
- contains "apples" at the end of the string :
apples$
- has any 3 characters between "app" and "les" :
app...les
- contains a letter or a digit at any position :
%w
- contains a digit at the end of the string :
%d$
- contains either "duck" or "luck" at any position :
[dl]uck
- does not contain a number between 0 and 4 at the start of the string :
^[^0-4]
- contains "]" at the end of the string :
%]$
- is either "apple" or "apples" :
apples?
- is "a", or "aa", or "aaa", or "aaaa"... :
a+
Use this Lua Pattern Tester to verify your pattern matches an example string.