Regular expression – Wikipedia
A regular expression, or RegEx, is a special formula that describes a string. They play an important role in the lexical analysis of text. A lexical scanner uses regular expressions to break down the source text into so-called tokens (keywords, operators, etc.), which can then be analyzed.
A common use of regular expressions is to find specific strings within a set of strings.
A good online tool is regex101: regex101: Online Regex Tester, Builder, Converter & Debugger
Regular Expressions in Practice
A regular expression is formed from the characters of the alphabet a–z, A–Z, and 0–9 in combination with the metacharacters [] () {} | ? + - * ^$ \ .
Characters that must match exactly (literally) are written as they appear.
Brackets ([ and ] or ( and )) can be used to define a character set.
- The expression in square brackets represents exactly one character from this set. In some cases, the meaning of a symbol depends on the context in which it appears within the brackets.
- The expression in parentheses is the string to be searched for.
| [aeiou] | searches all vowels in the text |
| [3-6] | get all numbers in range 3-6 |
| (eins) | get all strings “eins” |
pred-defined classes
| \d | digit | a digit, i.e., [0-9] (and possibly other numeric characters in Unicode, such as Bengali numerals) |
| \D | no digit | no digit a character that is not a digit, i.e., [^\d] |
| \w | word character | word character a letter, a digit, or an underscore, i.e., [a-zA-Z_0-9] (and possibly also non-Latin letters, e.g., umlauts) |
| \W | no word character | no word character a character that is neither a letter, a digit, nor an underscore, i.e., [^\w] |
| \s | whitespace | whitespace usually at least the space character and the class of control characters \f, \n, \r, \t, and \v |
| \S | no whitespace | no whitespace a character that is not whitespace, i.e., [^\s] |
| . | letter | (almost) any character |
Quantifiers
Quantifiers (also known as repetition factors) allow the preceding expression to appear a varying number of times in the string.
| {min,max} | The preceding expression must appear at least min times and no more than max times. |
| {n} | The preceding expression must occur exactly n times. This corresponds to {n,n}. |
| {0,max} | The preceding expression may occur at most max times. |
| {min,} | The preceding expression must occur at least min times. |
| ? | The preceding expression occurs zero or one time; it is “optional.” This corresponds to {0,1}. |
| + | The preceding expression must occur at least once, but may also occur multiple times. This corresponds to {1,}. |
| * | The preceding expression may occur any number of times, including zero times. This corresponds to {0,}. |