my-first-regex.md (2128B)
1 +++ 2 title = "My First RegEx" 3 date = 2021-01-21 4 [extra] 5 type = "post" 6 +++ 7 8 `(?<=\.\/IssuerIcons\/).*(?=\.png)` 9 <!-- more --> 10 11 ## What it does 12 13 Let's break it apart piece by piece. It's meant to return the filename 14 from a given path in a specific format. When given 15 `./IssuerIcons/Example.png`, the script should return `Example`. 16 17 The first section is a positive lookbehind: `(?<=\.\/IssuerIcons\/)`. 18 This asserts that the selected portion must by preceeded by 19 `./IssuerIcons/`. 20 21 The section section is a pattern match: `.*`. This matches all 22 characters, excluding newlines, of any length. 23 24 The third and final section is a positive lookforward: `(?=\.png)`. 25 This asserts that the selected portion must be followed by `.png`. 26 27 ## Background 28 29 Yesterday, I wrote my first regular expression. I've always regarded 30 regex as an arcane art of true shell wizards – and for the most part, 31 I still do. Now though, I've gotten a glimpse of their world. 32 33 I wrote this expression for [Tofu][tofu], an open-source 2FA app for 34 iOS. I had been thinking of making more "issuer icons" for the app 35 when I noticed that the icons were all designed in one Sketch file. 36 This could become a problem if two people were to edit the file at 37 one time, so I suggested a [solution][issue]. 38 39 The author got back to me with another idea: ditch Sketch altogether, 40 and replace it with a shell script that generates icons from a 41 directory of `png`s. I [wrote it][pr]. I've since refined it, with 42 help from [ThinkChaos][tc], to make it independent of any preceding 43 directories using `sed`: `sed -E 's:.+/(.+)\.png:\1:'`. 44 45 It was a really fun experience – I've never written bash before! It 46 reminded me a lot of Drew DeVault's post [Become shell literate][sl]. 47 I work primarily from my terminal, and am slowly working my way up to 48 true mastery – I'm nowhere near close, but this was a step in the right 49 direction. 50 51 [tofu]: https://www.tofuauth.com/ 52 [issue]: https://github.com/calleerlandsson/Tofu/issues/52 53 [pr]: https://github.com/calleerlandsson/Tofu/pull/60 54 [sl]: https://drewdevault.com/2020/12/12/Shell-literacy.html 55 [tc]: https://github.com/ThinkChaos