Code Explainers

Code explainers tagged #regex

javascript
function parseHexColor(hex) {
  const cleaned = hex.trim().replace(/^#/, '');
 
  const expand = (short) =>

Parsing hex colors into RGBA channels

parsing bitwise regex
Intermediate 7 steps
php
<?php
 
namespace App\Validation;
 

Building a reusable address form validator in PHP

validation error-accumulation regex
Intermediate 9 steps
typescript
export function isValidCardNumber(input: string): boolean {
  const digits = input.replace(/[\s-]/g, "");
 
  if (!/^\d{12,19}$/.test(digits)) {

Validating card numbers with the Luhn check

luhn-algorithm checksum input-validation
Intermediate 7 steps
typescript
interface UserAgentInfo {
  browser: { name: string; version: string };
  os: { name: string; version: string };
  device: 'mobile' | 'tablet' | 'desktop';

Parsing a user-agent string with ordered rules

regex parsing pattern-matching
Intermediate 9 steps
php
<?php
 
declare(strict_types=1);
 

Normalizing human names in PHP

unicode text-normalization transliteration
Intermediate 8 steps
rust
use once_cell::sync::Lazy;
use regex::Regex;
 
static CREDIT_CARD: Lazy<Regex> = Lazy::new(|| {

Redacting sensitive data from logs in Rust

regex lazy-initialization checksum-validation
Intermediate 9 steps
rust
use once_cell::sync::Lazy;
use regex::Regex;
 
static NON_ALPHANUMERIC: Lazy<Regex> = Lazy::new(|| Regex::new(r"[^a-z0-9]+").unwrap());

Building URL slugs in Rust

string-processing regex transliteration
Intermediate 8 steps
java
public final class CaseConverter {
 
    private static final Pattern CAMEL_BOUNDARY =
            Pattern.compile("([a-z0-9])([A-Z])|([A-Z]+)([A-Z][a-z])");

Converting camelCase to snake_case in Java

regex string-manipulation utility-class
Intermediate 7 steps
python
import pandas as pd
import numpy as np
 
 

Cleaning a customer DataFrame with pandas

data-cleaning regex normalization
Intermediate 9 steps
java
public final class EmailNormalizer {
 
    private static final Pattern EMAIL_PATTERN = Pattern.compile(
        "^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$"

Normalizing email addresses in Java

validation regex normalization
Intermediate 8 steps
typescript
type Masker = (value: string) => string;
 
const maskEmail: Masker = (value) => {
  const [local, domain] = value.split("@");

Recursively masking sensitive data for logs

recursion regex data-masking
Intermediate 9 steps
php
<?php
 
final class MarkdownParser
{

Building a small Markdown-to-HTML parser in PHP

state-machine parsing closures
Intermediate 10 steps
go
package humanize
 
import (
	"fmt"

Parsing human-readable byte sizes in Go

parsing regex lookup-table
Intermediate 8 steps
ruby
class TemplateInterpolator
  PLACEHOLDER = /\{\{\s*([\w.]+)\s*\}\}/
 
  def initialize(strict: false)

Interpolating templates with dotted keys in Ruby

regex string-interpolation hash-traversal
Intermediate 6 steps
python
from werkzeug.routing import BaseConverter, ValidationError
from flask import Flask, jsonify, abort
 
 

Custom URL converters in Flask

url-routing validation converters
Intermediate 6 steps
ruby
class Contact < ApplicationRecord
  PHONE_FORMATS = {
    "US" => /\A\+1\d{10}\z/,
    "GB" => /\A\+44\d{10}\z/,

Country-aware phone validation in Rails

validation callbacks regex
Intermediate 6 steps
rust
use once_cell::sync::Lazy;
use regex::Regex;
 
static LOG_LINE: Lazy<Regex> = Lazy::new(|| {

Parsing access logs with a lazy regex in Rust

regex lazy-initialization parsing
Intermediate 7 steps
javascript
function formatPhoneNumber(value) {
  const digits = value.replace(/\D/g, '').slice(0, 10);
  const parts = [];
 

Building a live phone number input mask

input-masking regex dom-events
Intermediate 7 steps