Lesson 2 · Unit 01
The editor
Regex search and replace with groups, and the tools that understand code
What you practise
- Search with regular expressions and replace with groups, multiple cursors, go to definition and rename, what a language server does for every editor
Try a question from this lesson
Pick one
You rename id to userId with a plain find-and-replace over the whole file (done here with sed). What does the line become?
echo 'const width = grid.id;' > a.js
sed 's/id/userId/g' a.jsCorrect answer
const wuserIdth = gruserId.userId;
Why
Plain search matches the letters id wherever they sit, including inside width and grid. A text tool has no idea what a variable is. You need a pattern that means "the whole word", or a tool that understands the code.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Search is a language
Flip the regex switch in your editor's search box and the pattern becomes a small language: \b is the edge of a word, . any one character, [0-9] one digit, + "one or more", ^ and $ the start and end of a line.
grep -E and sed -E read the same language, so a terminal is a good place to practise.
printf 'id\nwidth\nvalid id\n' > f.txt
grep -cE '\bid\b' f.txtConcept
Groups
Round brackets in a pattern capture what they match. In the replacement, \1 is the first group and \2 the second. Many editors write them $1 and $2.
One replace with groups can reorder the same pieces on a thousand lines at once.
echo 'Lovelace, Ada' > n.txt
sed -E 's/(\w+), (\w+)/\2 \1/' n.txtConcept
The language server
Go to definition, rename, completion and red squiggles all come from a language server: a separate program that parses your project and answers the editor's questions.
Editor and server talk over one shared protocol (LSP), so the same Python server works in every editor that speaks it.
9 more exercises in the app
- 3× fill the blanks
- 4× type the answer
- 1× match the pairs
- 1× order the lines
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.