Find: regex replace
The find bar's replace row can use a regular expression, whose parenthesised groups the replacement can reorder with $1, $2 and so on. doubled() computes price * 2 - this lesson rewrites it to 2 * price. To play it in the IDE: Help > Lessons > Finding…, or ek9 -ide -lesson find-regex-replace.
Start from
The code the lesson starts from: copy it into a file of your own and follow the steps.
shop.ek9
#!ek9 defines module lesson.finding.shop defines class Total total as Integer: 0 addItem() -> price as Integer //total grows by one item's price total += price subtotal() as pure <- rtn as Integer: total default operator ? defines function priceLabel() as pure -> price as Integer <- rtn as String: `Total: ${price}` doubled() as pure -> price as Integer <- rtn as Integer: price * 2 defines program ShowTotal() stdout <- Stdout() total <- Total() total.addItem(5) total.addItem(10) stdout.println(priceLabel(total.subtotal())) stdout.println("The running total is shown above") //EOF
receipt.ek9
#!ek9 defines module lesson.finding.shop defines function receiptFooter() as pure -> grandTotal as Integer <- rtn as String: `Grand total: ${grandTotal}` defines program ShowReceipt() stdout <- Stdout() total <- Total() total.addItem(20) stdout.println(receiptFooter(total.subtotal())) //EOF
till.ek9
#!ek9 defines module lesson.finding.till defines program ShowTill() stdout <- Stdout() total <- 0 total += 15 stdout.println(`Till total: ${total}`) //EOF
Step 1: Open Replace
Choose Edit > Replace…
Step 2: A regular expression
Turn on the regular expression toggle (.*), then type (\w+) * (\d) into the field - a word, then * , then a digit, each side held in its own group. One match.
Step 3: Replace with a capture group
Type $2 * $1 into the Replace field - the digit first, then the word: the two groups swapped. Choose Replace All.
Text mode changes this file's buffer, not yet saved. Choose File > Save.
The result
That is a regular expression's capture groups used in the replacement: price * 2 read, and reordered into 2 * price. Replace changes only the current match; Replace All - just used - changes every match in the file. Text mode edits the buffer, so the file is saved before it is really changed.




