bjorn.now

#regex

One of my first loves as a programming language, I learned about it while working with PHP and how it allowed me work with text was mind blowing at the time. I ended up learning Perl because of 'em.

09 October, 2025

Don’t quote regex patterns in Bash [[ ]] tests, because they’ll match literally.

So the below won’t match because it’s looking for a literal $ in the string, instead of matching at the end of the string:

file="https://example.com/blog-post/index.html"
[[ "$file" =~ "/index.html$" ]] && echo MATCH

But this will:

file="https://example.com/blog-post/index.html"
[[ "$file" =~ /index\.html$ ]] && echo MATCH

Note: [[ ]] is a Bash extension of the test command that supports regexes (among other things). The [ ] is the POSIX standard test (see man test), so [[ ]] features may not work in other shells or in limited shells like ash or sh.

[… more]
til 1 min read #bash, #regex, #shell-scripting

08 October, 2025

The regex | (or) operator splits the pattern left or right unless explicitly grouped. Group it using (pattern) if you need to use the match later, or as a non-capturing group (?:pattern) if you do it for clarity.

I used to think there was some magic rule about how | decided where to split, but it’s simply: characters and subpatterns concatenate into a single pattern first, then | splits the entire thing left and right unless you explicitly group it. That’s because | has the lowest precedence so all other operations happen first.

So while I used to think that prefix_cat|dog would match prefix_cat and prefix_dog, it actually matches prefix_cat and then dog.

And that exact problem in a real-world example, to find if a page is linking to another, both relative or full URL:

[… more]
til Updated 2 min read #how-to, #regex, #background-work