Regular expressions
What it is #
A regular expression is a pattern for searching text. The bot uses a simplified RE2: the text is scanned strictly left to right, which keeps expressions simple and fast.
Two conveniences: you do not need the usual slashes around the pattern, and case is ignored — lower case is enough.
The simplest case: a list of words #
In the simplest case a regular expression is just a list of words separated by |:
крипта|работа|p2p— matches a message containing any of the threevpn[a-z0-9_]+bot— any username that starts with vpn and ends with bot
That is already enough for a word blacklist.
A worked example #
One expression can cover dozens of spellings at once:
[uюу]+.?[$зsсc]+.?[dд]+.?[tт]+
It matches all of these:
usdtussssdtu$d!tU зDTюс дт
The sets list look-alike letters from different alphabets, + allows repeats, and .? allows any single character in between — or none at all.
Character sets: [ ] #
Square brackets list the characters allowed in this position — one by one or as ranges:
[uюу]— u, ю or у here[a-z],[а-я],[0-9]— ranges[а-яa-z0-9]— ranges can be combined
A dot . outside brackets means any character at all.
Quantifiers: ? + * {X,Y} #
Put them after a character, a set or a group to say how many repeats are allowed:
?— zero or one+— one or more*— zero or more{2,5}— from two to five{2,}— two or more
A single character needs no quantifier at all.
Anchors: ^ and $ #
Without them the pattern is searched anywhere in the text.
^at the start — pin the match to the beginning of the string$at the end — pin it to the end^\p{Extended_Pictographic}$— the whole message is a single emoji and nothing else
Negation: [^ ] #
The same caret, but placed right after the opening bracket, inverts the set:
[^0-9]— any character except a digit[^а-яё ]— anything but a Russian letter or a space
Anywhere else inside the set the caret is just an ordinary character.
Groups and alternatives: ( ) and | #
Brackets group words the way square brackets group characters, and | lists the options:
(куплю|покупаю|скупаю) крипту— matches all three phrases at once(бот|bot)$— the message ends with either spelling
The brackets are an operator — they are not searched for in the text.
Shortcuts #
Handy replacements for common sets:
\d— a digit, same as[0-9]\w— a letter, digit or underscore:[A-Za-z0-9_]\s— a space, tab or line break\b— a word boundary\R— any kind of line break
A capital letter negates the shortcut: \D, \W, \S, \B.
Whole alphabets are available too:
\p{Cyrillic}— Cyrillic\p{Latin}— Latin\p{Han}— Chinese characters\p{Arabic}— Arabic\p{Extended_Pictographic}— emoji