Codele / Advanced programming
Regular expressions
A regular expression is a stencil for text: you describe a shape, such as “some digits, a dash, more digits”, and the computer slides it along the text to see if it fits.
- A regular expression (often shortened to regex) is a pattern for text. The computer slides it along a string and says whether it fits.
- \d is one digit, + means one or more, ? means optional, and ( ) make a group whose caught text you can read afterwards. ^ and $ pin the start and the end.
- Python, JavaScript, Java, C#, C++ (the regex library) and Go (the regexp package) all read these basic pieces the same way. Fancier features differ, so keep patterns small.
- Backslashes need care. Java and C++ strings write \\d for \d; Python, C# and Go have raw strings (r"…", @"…", backticks) that keep it as \d; JavaScript uses /…/.
- No match is not an error. Python and JavaScript give back None or null, Java and C# say false, Go gives nil, so always check before reading a group.
Loading the playable lesson…