Programming Search⌘K

Taskcore

Find and replace with a regular expression

Also called regex replace, replace with a regex, find all matches of a regex, use capture groups, escape a string for a regex, regex substitution with a back reference.

Find each date YYYY-MM-DD in a text with a regular expression, return its capture groups, and write it as DD/MM/YYYY through references to the groups, with literal separators.

Task

Find each date in a text and write it in another order. A date is YYYY-MM-DD with ASCII digits and no ASCII digit just before it or just after it. The result has DD/MM/YYYY in its place. The two separators are parameters, and each one is a literal string.

The contract has two entries:

  • reformat_dates(text, from_sep, to_sep) returns the text with each date YYYY<from_sep>MM<from_sep>DD changed to DD<to_sep>MM<to_sep>YYYY. The rest of the text does not change.
  • find_dates(text, sep) returns the list [year, month, day] of the capture groups of each date, in order. Its cases are in cases/find.jsonl.

The search goes from left to right, and two dates do not overlap. A match that fails the digit check does not hide a date that starts later inside it. The task checks the shape of a date only, so 2024-13-45 is a date here.

Solutions

Each solution makes the pattern from three parts. The year, month and day are capture groups of [0-9] digits. The separator is escaped, so a . in it matches only a dot. The digit check uses the lookbehind (?<![0-9]) and the lookahead (?![0-9]) where the engine has them. The replacement refers to the groups by name, so a digit after a reference is not part of the reference. The separator in the replacement is escaped for the replacement syntax.

  • Python. re.escape escapes the separator. re.sub replaces each match, and \g<day> refers to the group (?P<day>...). In a replacement string, a backslash starts an escape, so the code doubles each backslash of to_sep. finditer and Match.groups() give the groups for find_dates.
  • JavaScript and TypeScript (Node.js). RegExp.escape escapes the separator. replaceAll needs the flag g, and it throws a TypeError without it. In the replacement, $<day> refers to a named group and $$ gives one $, so the code changes each $ of toSep to $$. matchAll gives the groups.
  • Java. Pattern.quote escapes the separator. Matcher.replaceAll takes ${day} for a named group. Matcher.quoteReplacement escapes $ and \ in toSep. Matcher.results() gives one MatchResult for each match.
  • C#. Regex.Escape escapes the separator. Regex.Replace takes ${day}, and $$ gives one $. Matches gives the groups.
  • Go. regexp.QuoteMeta escapes the separator. Go does not accept lookbehind or lookahead (see the pitfalls), so the pattern has no digit check. A loop calls FindStringSubmatchIndex and checks the bytes next to each match. If the check fails, the next search starts one byte after the start of the failed match, so a date inside it is still found. Expand writes the template ${day} and the other groups.
  • C. regex.h has regcomp, regexec, regerror and regfree. None of them escapes a string or replaces a match, so reformat_dates.c does both. It puts a backslash before each ERE special character of the separator. regcomp with REG_EXTENDED compiles the pattern. regexec gives a regmatch_t for each group, with the byte offsets rm_so and rm_eo. The digit check and the restart are the same as in Go.
  • C++. std::regex uses the modified ECMAScript grammar by default. Its assertions are ^, $, \b, \B, (?=...) and (?!...), so it has no lookbehind. The library has regex_match, regex_search and regex_replace, and no function that escapes a string, so the code has its own. A loop calls regex_search and does the digit check. The result is built from m.str(3), m.str(2) and m.str(1), so the separator is never read as a format.
  • Bash. [[ string =~ regex ]] matches a POSIX extended regular expression, and a quoted part of the pattern matches as a literal string. So "$3" in the pattern is the separator with no escape. BASH_REMATCH holds the groups. The function tries a match at each position with ^, checks the digits next to it, and builds the result in a string. local LC_ALL=C makes each byte one character, so the offsets count bytes.

Rust has no regular expressions in its standard library. This page uses the crate regex at version 1.13.1, so the Rust program is a page example and not a tested solution. The file matrix.yaml records this. The crate has no look-around, so the code does the digit check as in Go. captures_at starts a search at an offset and still sees the text before it:

use regex::{Captures, Regex};

/// Returns the pattern of a date YYYY<sep>MM<sep>DD. The crate has no
/// look-around, so the pattern does not check the digits next to the date.
fn date_pattern(sep: &str) -> Regex {
    // regex::escape makes each special character of sep match only itself.
    let s = regex::escape(sep);
    Regex::new(&format!(r"(?<year>[0-9]{{4}}){s}(?<month>[0-9]{{2}}){s}(?<day>[0-9]{{2}})")).unwrap()
}

fn is_digit_at(text: &str, i: usize) -> bool {
    text.as_bytes().get(i).is_some_and(u8::is_ascii_digit)
}

/// Returns the captures of each date in text that has no digit next to it.
fn dates<'t>(re: &Regex, text: &'t str) -> Vec<Captures<'t>> {
    let mut found = Vec::new();
    let mut pos = 0;
    while let Some(c) = re.captures_at(text, pos) {
        let m = c.get(0).unwrap();
        if (m.start() > 0 && is_digit_at(text, m.start() - 1)) || is_digit_at(text, m.end()) {
            // A date can start inside this match. m.start() is an ASCII digit,
            // so m.start() + 1 is the start of a character.
            pos = m.start() + 1;
            continue;
        }
        pos = m.end();
        found.push(c);
    }
    found
}

/// Changes each date YYYY<from_sep>MM<from_sep>DD in text to DD<to_sep>MM<to_sep>YYYY.
fn reformat_dates(text: &str, from_sep: &str, to_sep: &str) -> String {
    let mut out = String::new();
    let mut last = 0;
    for c in dates(&date_pattern(from_sep), text) {
        let m = c.get(0).unwrap();
        out.push_str(&text[last..m.start()]);
        // to_sep is pushed as it is, so a $ in it has no special meaning.
        for part in [&c["day"], to_sep, &c["month"], to_sep, &c["year"]] {
            out.push_str(part);
        }
        last = m.end();
    }
    out.push_str(&text[last..]);
    out
}

fn main() {
    println!("{}", reformat_dates("Due 2024-01-02.", "-", "/"));
    println!("{}", reformat_dates("2024-01-0234-05-06", "-", "/"));
    println!("{}", reformat_dates("2024.01.02 2024x01x02", ".", "$1"));
    for c in dates(&date_pattern("-"), "12024-01-02 2024-01-02 2025-12-31") {
        println!("{} {} {}", &c["year"], &c["month"], &c["day"]);
    }
}
Output
Due 02/01/2024.
2024-01-06/05/0234
02$101$12024 2024x01x02
2024 01 02
2025 12 31

Syntax between engines

Engine Named group Reference in a replacement Literal $ \d Lookbehind
Python re (?P<n>...) \g<n>, \g<1> $ Unicode digits yes
JavaScript (?<n>...) $<n>, $1 $$ [0-9] yes
Java (?<n>...) ${n}, $1 \$ [0-9] yes
.NET (?<n>...) ${n}, $1 $$ Unicode digits yes
Go regexp (?P<n>...), (?<n>...) ${n}, $1 $$ [0-9] no
Rust regex (?P<n>...), (?<n>...) ${n}, $1 $$ Unicode digits no
POSIX ERE (C, Bash) none none not special none no

In Python, a backslash in the replacement starts an escape such as \n. In Java, a backslash escapes the next character. In Go and Rust, $1x is the group named 1x, so write ${1}x. In Java, $12 is group 12 only if the pattern has 12 groups. In Python, \20 is group 20, and \g<2>0 is group 2 and a 0. Java sets \d to Unicode digits with the flag UNICODE_CHARACTER_CLASS. .NET sets it to [0-9] with RegexOptions.ECMAScript.

Backtracking and linear time

The default engines of Python and .NET backtrack. For some patterns, such as ^(a+)+$, the time of a failed match grows exponentially with the length of the text. Go regexp runs in time linear in the size of the input. The Rust crate regex has a worst case of O(m × n) for a pattern of size m and a text of size n. Both engines have no lookaround and no back references. .NET has the option RegexOptions.NonBacktracking, which is linear in the length of the input, and a time-out for each match. Python has possessive quantifiers and atomic groups, which stop the backtracking in one part of a pattern. A pattern from a user, or a pattern with nested quantifiers on text from a user, is a risk of Uncontrolled resource consumption. The pattern of this task has a fixed length and no nested quantifier, so the work at each start position has a fixed limit.

Edge cases

The cases are in cases/basic.jsonl, cases/edge.jsonl and cases/find.jsonl.

  • empty-text and empty-to-sep: an empty text gives an empty result. An empty to_sep joins the parts.
  • whole-text, adjacent and multiline: a date at the start or the end of the text, two dates with a comma between them, and dates on separate lines. The pattern has no ^ or $, so no multiline flag is needed.
  • digit-before and digit-after: 12024-01-02 and 2024-01-023 hold no date. Without the digit check, a search finds 2024-01-02 inside them.
  • date-after-rejected: in 2024-01-0234-05-06, the first match 2024-01-02 fails the digit check, and the date 0234-05-06 starts inside it. A loop that goes on after the end of a failed match misses this date. A lookbehind, or a restart one character after the start of the failed match, finds it.
  • chained: in 2024-01-02-03, the first date is replaced and -03 stays.
  • other-separator, dot-separator, backslash-separator and plus-separator: the separator matches only itself. An unescaped . matches the x of 2024x01x02, an unescaped + makes 0+ mean one or more zeros, and an unescaped \ is an error or an escape.
  • dollar-in-replacement, backslash-in-replacement, digit-in-replacement and whole-match-in-replacement: $1, \1\, 0 and $& as to_sep are copied as they are. A 0 after a numbered reference such as $2 can make the reference $20, which the named groups avoid.
  • unicode-digits: Arabic-Indic digits and fullwidth digits are not dates, so \d is wrong in Python, .NET and Rust.
  • non-ascii-text and non-ascii-separator: text with an emoji, and the separator – (U+2013). Go, C, C++, Rust and Bash work on UTF-8 bytes. The restart after a failed match moves one byte, and that byte is an ASCII digit, so the next search starts at the start of a character.
  • not-a-calendar-date: 2024-13-45 becomes 45/13/2024. To check the calendar, parse each match as a date.

Pitfalls

  • \d matches more than ASCII digits. In Python, .NET and the Rust crate, \d matches each Unicode decimal digit. A later int() or a date parser then gets text that it did not expect. Use [0-9], or the flag re.ASCII in Python:

This code runs but gives a wrong answer on purpose.

import re

text = "٢٠٢٤-٠١-٠٢ 2024-01-02"
print(re.findall(r"\d{4}-\d{2}-\d{2}", text))
print(re.findall(r"\d{4}-\d{2}-\d{2}", text, flags=re.ASCII))
Output
['٢٠٢٤-٠١-٠٢', '2024-01-02']
['2024-01-02']
  • re.match checks only the start. re.match anchors the pattern at the start of the text, but not at the end. So a check of the whole text with re.match accepts text after the date. Use re.fullmatch:

This code runs but gives a wrong answer on purpose.

import re

date = r"[0-9]{4}-[0-9]{2}-[0-9]{2}"
for text in ["2024-01-02", "2024-01-02; rm -rf /"]:
    print(repr(text), bool(re.match(date, text)), bool(re.fullmatch(date, text)))
Output
'2024-01-02' True True
'2024-01-02; rm -rf /' True False
  • A $ in the replacement is a group reference. In Java, a value such as $1.50 refers to group 1, and the call throws. A function that returns the replacement does not help, because Java parses its result in the same way. Matcher.quoteReplacement makes the value literal:

This code runs but gives a wrong answer on purpose.

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    public static void main(String[] args) {
        Pattern price = Pattern.compile("\\{price\\}");
        String value = "$1.50";
        try {
            System.out.println(price.matcher("Cost: {price}").replaceAll(value));
        } catch (IndexOutOfBoundsException e) {
            System.out.println(e.getMessage());
        }
        try {
            System.out.println(price.matcher("Cost: {price}").replaceAll(m -> value));
        } catch (IndexOutOfBoundsException e) {
            System.out.println(e.getMessage());
        }
        System.out.println(price.matcher("Cost: {price}").replaceAll(Matcher.quoteReplacement(value)));
    }
}
Output
No group 1
No group 1
Cost: $1.50
  • $3_ in Go is the group named 3_. Go takes the longest name after $, and a missing group gives an empty string. Write ${3}_:

This code runs but gives a wrong answer on purpose.

package main

import (
	"fmt"
	"regexp"
)

func main() {
	re := regexp.MustCompile(`([0-9]{4})-([0-9]{2})-([0-9]{2})`)
	fmt.Printf("%q\n", re.ReplaceAllString("2024-01-02", "$3_$2_$1"))
	fmt.Printf("%q\n", re.ReplaceAllString("2024-01-02", "${3}_${2}_${1}"))
}
Output
"2024"
"02_01_2024"
  • Go rejects lookbehind, lookahead and back references. A pattern from another engine can fail to compile in Go. The error message does not always name the feature:
package main

import (
	"fmt"
	"regexp"
)

func main() {
	for _, expr := range []string{`(?<![0-9])[0-9]{4}`, `[0-9]{4}(?![0-9])`, `([0-9])\1`} {
		_, err := regexp.Compile(expr)
		fmt.Println(err)
	}
}
Output
error parsing regexp: invalid named capture: `(?<![0-9])[0-9]{4}`
error parsing regexp: invalid or unsupported Perl syntax: `(?!`
error parsing regexp: invalid escape sequence: `\1`
  • A regular expression with the flag g keeps state. In JavaScript, test and exec on a regular expression with g start at lastIndex, and a match sets lastIndex to its end. A shared pattern then fails on every second call. Use a pattern without g for a test:

This code runs but gives a wrong answer on purpose.

const date = /[0-9]{4}-[0-9]{2}-[0-9]{2}/g;
for (const text of ["2024-01-02", "2024-01-03", "2024-01-04"]) {
  console.log(text, date.test(text), date.lastIndex);
}
Output
2024-01-02 true 10
2024-01-03 false 0
2024-01-04 true 10
  • A backtracking engine can take exponential time. The .NET documentation gives ^(a+)+$ as an example. A time-out stops the match, and RegexOptions.NonBacktracking gives the answer in linear time:
using System.Text.RegularExpressions;

string text = new string('a', 40) + "!";
var timeout = TimeSpan.FromMilliseconds(200);
try
{
    Console.WriteLine(new Regex("^(a+)+$", RegexOptions.None, timeout).IsMatch(text));
}
catch (RegexMatchTimeoutException)
{
    Console.WriteLine("backtracking: timed out");
}
Console.WriteLine("non-backtracking: " + new Regex("^(a+)+$", RegexOptions.NonBacktracking).IsMatch(text));
Output
backtracking: timed out
non-backtracking: False

Code

The build runs the native tests of each language in a pinned toolchain.

reformat_dates.pyI0tests passRawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/find-and-replace-with-a-regular-expression/.

import re


def date_pattern(sep: str) -> re.Pattern[str]:
    """Return the pattern of a date YYYY<sep>MM<sep>DD with no digit next to it."""
    # re.escape makes each special character of sep match only itself.
    # [0-9] is ASCII only. \d also matches other decimal digits, such as ٢.
    s = re.escape(sep)
    return re.compile(rf"(?<![0-9])(?P<year>[0-9]{{4}}){s}(?P<month>[0-9]{{2}}){s}(?P<day>[0-9]{{2}})(?![0-9])")


def reformat_dates(text: str, from_sep: str, to_sep: str) -> str:
    """Change each date YYYY<from_sep>MM<from_sep>DD in text to DD<to_sep>MM<to_sep>YYYY."""
    # In a replacement template, a backslash starts an escape, so to_sep doubles each one.
    # \g<day> ends at ">", so a digit after it is not part of the group name.
    sep = to_sep.replace("\\", "\\\\")
    return date_pattern(from_sep).sub(rf"\g<day>{sep}\g<month>{sep}\g<year>", text)


def find_dates(text: str, sep: str) -> list[list[str]]:
    """Return [year, month, day] for each date YYYY<sep>MM<sep>DD in text."""
    return [list(m.groups()) for m in date_pattern(sep).finditer(text)]
test_reformat_dates.py 63 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/find-and-replace-with-a-regular-expression/.

import re

import pytest

from reformat_dates import find_dates, reformat_dates

CASES = {
    "one-date": ("Due 2024-01-02.", "-", "/", "Due 02/01/2024."),
    "two-dates": ("From 2024-01-02 to 2024-12-31", "-", "/", "From 02/01/2024 to 31/12/2024"),
    "no-date": ("no dates here", "-", "/", "no dates here"),
    "empty-text": ("", "-", "/", ""),
    "empty-to-sep": ("2024-01-02", "-", "", "02012024"),
    "whole-text": ("2024-01-02", "-", "/", "02/01/2024"),
    "adjacent": ("2024-01-02,2024-01-03", "-", "/", "02/01/2024,03/01/2024"),
    "digit-before": ("12024-01-02", "-", "/", "12024-01-02"),
    "digit-after": ("2024-01-023", "-", "/", "2024-01-023"),
    "date-after-rejected": ("2024-01-0234-05-06", "-", "/", "2024-01-06/05/0234"),
    "chained": ("2024-01-02-03", "-", "/", "02/01/2024-03"),
    "other-separator": ("2024/01/02", "-", ".", "2024/01/02"),
    "dot-separator": ("2024x01x02 2024.01.02", ".", "-", "2024x01x02 02-01-2024"),
    "backslash-separator": ("2024\\01\\02", "\\", "-", "02-01-2024"),
    "plus-separator": ("2024+01+02 202401102", "+", "-", "02-01-2024 202401102"),
    "dollar-in-replacement": ("2024-01-02", "-", "$1", "02$101$12024"),
    "backslash-in-replacement": ("2024-01-02", "-", "\\1\\", "02\\1\\01\\1\\2024"),
    "digit-in-replacement": ("2024-01-02", "-", "0", "0200102024"),
    "whole-match-in-replacement": ("2024-01-02", "-", "$&", "02$&01$&2024"),
    "unicode-digits": ("٢٠٢٤-٠١-٠٢ and 2024-01-02 and 2024-01-02", "-", "/", "٢٠٢٤-٠١-٠٢ and 2024-01-02 and 02/01/2024"),
    "non-ascii-text": ("Café ☕ 2024-01-02 🙂", "-", "/", "Café ☕ 02/01/2024 🙂"),
    "non-ascii-separator": ("2024–01–02", "–", "·", "02·01·2024"),
    "multiline": ("2024-01-02\n2024-01-03\n", "-", "/", "02/01/2024\n03/01/2024\n"),
    "not-a-calendar-date": ("2024-13-45", "-", "/", "45/13/2024"),
}

FIND_CASES = {
    "two-dates": ("From 2024-01-02 to 2024-12-31", "-", [["2024", "01", "02"], ["2024", "12", "31"]]),
    "none": ("no dates here", "-", []),
    "empty": ("", "-", []),
    "date-after-rejected": ("2024-01-0234-05-06", "-", [["0234", "05", "06"]]),
    "dot-separator": ("2024x01x02 2024.01.02", ".", [["2024", "01", "02"]]),
    "unicode-digits": ("٢٠٢٤-٠١-٠٢ 2024-01-02", "-", [["2024", "01", "02"]]),
}


@pytest.mark.parametrize("name", CASES)
def test_reformat_dates(name):
    text, from_sep, to_sep, want = CASES[name]
    assert reformat_dates(text, from_sep, to_sep) == want


@pytest.mark.parametrize("name", FIND_CASES)
def test_find_dates(name):
    text, sep, want = FIND_CASES[name]
    assert find_dates(text, sep) == want


def test_full_match():
    # match anchors only at the start; fullmatch anchors at both ends.
    pattern = r"[0-9]{4}-[0-9]{2}-[0-9]{2}"
    assert re.match(pattern, "2024-01-02x") is not None
    assert re.fullmatch(pattern, "2024-01-02x") is None
reformat_dates.cppI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/find-and-replace-with-a-regular-expression/.

#include "reformat_dates.hpp"

#include <regex>
#include <string_view>

namespace {

// Returns s with a backslash before each special character of an ECMAScript pattern. The standard library has no
// function for this.
std::string escape(std::string_view s) {
    std::string out;
    for (char c : s) {
        if (std::string_view{R"(^$\.*+?()[]{}|)"}.contains(c)) {
            out += '\\';
        }
        out += c;
    }
    return out;
}

// The pattern of a date YYYY<sep>MM<sep>DD. The code checks the digits next to the date, because std::regex has no
// lookbehind.
std::regex date_pattern(const std::string& sep) {
    std::string s = escape(sep);
    return std::regex("([0-9]{4})" + s + "([0-9]{2})" + s + "([0-9]{2})");
}

bool is_digit_at(const std::string& text, std::size_t i) {
    return i < text.size() && text[i] >= '0' && text[i] <= '9';
}

// Calls f with each date in text that has no digit next to it.
template <typename F>
void each_date(const std::string& text, const std::regex& re, F f) {
    std::size_t pos = 0;
    std::smatch m;
    while (pos < text.size() && std::regex_search(text.begin() + static_cast<std::ptrdiff_t>(pos), text.end(), m, re)) {
        std::size_t start = pos + static_cast<std::size_t>(m.position(0));
        std::size_t end = start + static_cast<std::size_t>(m.length(0));
        if ((start > 0 && is_digit_at(text, start - 1)) || is_digit_at(text, end)) {
            pos = start + 1;  // a date can start inside this match
            continue;
        }
        f(start, end, m);
        pos = end;
    }
}

}  // namespace

std::string reformat_dates(const std::string& text, const std::string& from_sep, const std::string& to_sep) {
    std::string out;
    std::size_t last = 0;
    each_date(text, date_pattern(from_sep), [&](std::size_t start, std::size_t end, const std::smatch& m) {
        out.append(text, last, start - last);
        out += m.str(3) + to_sep + m.str(2) + to_sep + m.str(1);
        last = end;
    });
    out.append(text, last);
    return out;
}

std::vector<std::array<std::string, 3>> find_dates(const std::string& text, const std::string& sep) {
    std::vector<std::array<std::string, 3>> dates;
    each_date(text, date_pattern(sep), [&](std::size_t, std::size_t, const std::smatch& m) {
        dates.push_back({m.str(1), m.str(2), m.str(3)});
    });
    return dates;
}
reformat_dates.hpp 14 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/find-and-replace-with-a-regular-expression/.

#pragma once

#include <array>
#include <string>
#include <vector>

// Changes each date YYYY<from_sep>MM<from_sep>DD in text to DD<to_sep>MM<to_sep>YYYY.
std::string reformat_dates(const std::string& text, const std::string& from_sep, const std::string& to_sep);

// Returns {year, month, day} for each date YYYY<sep>MM<sep>DD in text.
std::vector<std::array<std::string, 3>> find_dates(const std::string& text, const std::string& sep);
test_reformat_dates.cpp 82 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/find-and-replace-with-a-regular-expression/.

#include <cstdio>
#include <string>
#include <vector>

#include "reformat_dates.hpp"

namespace {

struct test_case {
    const char *name, *text, *from_sep, *to_sep, *want;
};

const test_case cases[] = {
    {"one-date", "Due 2024-01-02.", "-", "/", "Due 02/01/2024."},
    {"two-dates", "From 2024-01-02 to 2024-12-31", "-", "/", "From 02/01/2024 to 31/12/2024"},
    {"no-date", "no dates here", "-", "/", "no dates here"},
    {"empty-text", "", "-", "/", ""},
    {"empty-to-sep", "2024-01-02", "-", "", "02012024"},
    {"whole-text", "2024-01-02", "-", "/", "02/01/2024"},
    {"adjacent", "2024-01-02,2024-01-03", "-", "/", "02/01/2024,03/01/2024"},
    {"digit-before", "12024-01-02", "-", "/", "12024-01-02"},
    {"digit-after", "2024-01-023", "-", "/", "2024-01-023"},
    {"date-after-rejected", "2024-01-0234-05-06", "-", "/", "2024-01-06/05/0234"},
    {"chained", "2024-01-02-03", "-", "/", "02/01/2024-03"},
    {"other-separator", "2024/01/02", "-", ".", "2024/01/02"},
    {"dot-separator", "2024x01x02 2024.01.02", ".", "-", "2024x01x02 02-01-2024"},
    {"backslash-separator", "2024\\01\\02", "\\", "-", "02-01-2024"},
    {"plus-separator", "2024+01+02 202401102", "+", "-", "02-01-2024 202401102"},
    {"dollar-in-replacement", "2024-01-02", "-", "$1", "02$101$12024"},
    {"backslash-in-replacement", "2024-01-02", "-", "\\1\\", "02\\1\\01\\1\\2024"},
    {"digit-in-replacement", "2024-01-02", "-", "0", "0200102024"},
    {"whole-match-in-replacement", "2024-01-02", "-", "$&", "02$&01$&2024"},
    {"unicode-digits", "٢٠٢٤-٠١-٠٢ and 2024-01-02 and 2024-01-02", "-", "/", "٢٠٢٤-٠١-٠٢ and 2024-01-02 and 02/01/2024"},
    {"non-ascii-text", "Café ☕ 2024-01-02 🙂", "-", "/", "Café ☕ 02/01/2024 🙂"},
    {"non-ascii-separator", "2024–01–02", "–", "·", "02·01·2024"},
    {"multiline", "2024-01-02\n2024-01-03\n", "-", "/", "02/01/2024\n03/01/2024\n"},
    {"not-a-calendar-date", "2024-13-45", "-", "/", "45/13/2024"},
};

// Each date is written as "year-month-day", and the dates are joined by spaces.
struct find_case {
    const char *name, *text, *sep, *want;
};

const find_case find_cases[] = {
    {"two-dates", "From 2024-01-02 to 2024-12-31", "-", "2024-01-02 2024-12-31"},
    {"none", "no dates here", "-", ""},
    {"empty", "", "-", ""},
    {"date-after-rejected", "2024-01-0234-05-06", "-", "0234-05-06"},
    {"dot-separator", "2024x01x02 2024.01.02", ".", "2024-01-02"},
    {"unicode-digits", "٢٠٢٤-٠١-٠٢ 2024-01-02", "-", "2024-01-02"},
};

}  // namespace

int main() {
    int failed = 0;
    for (const auto& c : cases) {
        if (std::string got = reformat_dates(c.text, c.from_sep, c.to_sep); got != c.want) {
            std::fprintf(stderr, "FAIL %s: got \"%s\"\n", c.name, got.c_str());
            ++failed;
        }
    }
    for (const auto& c : find_cases) {
        std::string got;
        for (const auto& [year, month, day] : find_dates(c.text, c.sep)) {
            got += (got.empty() ? "" : " ") + year + "-" + month + "-" + day;
        }
        if (got != c.want) {
            std::fprintf(stderr, "FAIL %s: got \"%s\"\n", c.name, got.c_str());
            ++failed;
        }
    }
    if (failed > 0) {
        return 1;
    }
    std::puts("ok");
    return 0;
}
ReformatDates.javaI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/find-and-replace-with-a-regular-expression/.

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/** Finds dates with a regular expression and writes them in another order. */
public final class ReformatDates {
    private ReformatDates() {}

    /** Returns the pattern of a date YYYY(sep)MM(sep)DD with no digit next to it. */
    static Pattern datePattern(String sep) {
        // Pattern.quote makes each special character of sep match only itself.
        String s = Pattern.quote(sep);
        return Pattern.compile("(?<![0-9])(?<year>[0-9]{4})" + s + "(?<month>[0-9]{2})" + s
                + "(?<day>[0-9]{2})(?![0-9])");
    }

    /** Changes each date YYYY(fromSep)MM(fromSep)DD in text to DD(toSep)MM(toSep)YYYY. */
    public static String reformatDates(String text, String fromSep, String toSep) {
        // In a replacement string, $ starts a group reference and \ escapes the next character.
        String sep = Matcher.quoteReplacement(toSep);
        return datePattern(fromSep).matcher(text).replaceAll("${day}" + sep + "${month}" + sep + "${year}");
    }

    /** Returns [year, month, day] for each date YYYY(sep)MM(sep)DD in text. */
    public static List<List<String>> findDates(String text, String sep) {
        return datePattern(sep).matcher(text).results()
                .map(m -> List.of(m.group("year"), m.group("month"), m.group("day")))
                .toList();
    }
}
ReformatDatesTest.java 64 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/find-and-replace-with-a-regular-expression/.

import static org.junit.jupiter.api.Assertions.assertEquals;

import java.util.List;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

class ReformatDatesTest {
    static Stream<Arguments> cases() {
        return Stream.of(
                Arguments.of("one-date", "Due 2024-01-02.", "-", "/", "Due 02/01/2024."),
                Arguments.of("two-dates", "From 2024-01-02 to 2024-12-31", "-", "/", "From 02/01/2024 to 31/12/2024"),
                Arguments.of("no-date", "no dates here", "-", "/", "no dates here"),
                Arguments.of("empty-text", "", "-", "/", ""),
                Arguments.of("empty-to-sep", "2024-01-02", "-", "", "02012024"),
                Arguments.of("whole-text", "2024-01-02", "-", "/", "02/01/2024"),
                Arguments.of("adjacent", "2024-01-02,2024-01-03", "-", "/", "02/01/2024,03/01/2024"),
                Arguments.of("digit-before", "12024-01-02", "-", "/", "12024-01-02"),
                Arguments.of("digit-after", "2024-01-023", "-", "/", "2024-01-023"),
                Arguments.of("date-after-rejected", "2024-01-0234-05-06", "-", "/", "2024-01-06/05/0234"),
                Arguments.of("chained", "2024-01-02-03", "-", "/", "02/01/2024-03"),
                Arguments.of("other-separator", "2024/01/02", "-", ".", "2024/01/02"),
                Arguments.of("dot-separator", "2024x01x02 2024.01.02", ".", "-", "2024x01x02 02-01-2024"),
                Arguments.of("backslash-separator", "2024\\01\\02", "\\", "-", "02-01-2024"),
                Arguments.of("plus-separator", "2024+01+02 202401102", "+", "-", "02-01-2024 202401102"),
                Arguments.of("dollar-in-replacement", "2024-01-02", "-", "$1", "02$101$12024"),
                Arguments.of("backslash-in-replacement", "2024-01-02", "-", "\\1\\", "02\\1\\01\\1\\2024"),
                Arguments.of("digit-in-replacement", "2024-01-02", "-", "0", "0200102024"),
                Arguments.of("whole-match-in-replacement", "2024-01-02", "-", "$&", "02$&01$&2024"),
                Arguments.of("unicode-digits", "٢٠٢٤-٠١-٠٢ and 2024-01-02 and 2024-01-02", "-", "/", "٢٠٢٤-٠١-٠٢ and 2024-01-02 and 02/01/2024"),
                Arguments.of("non-ascii-text", "Café ☕ 2024-01-02 🙂", "-", "/", "Café ☕ 02/01/2024 🙂"),
                Arguments.of("non-ascii-separator", "2024–01–02", "–", "·", "02·01·2024"),
                Arguments.of("multiline", "2024-01-02\n2024-01-03\n", "-", "/", "02/01/2024\n03/01/2024\n"),
                Arguments.of("not-a-calendar-date", "2024-13-45", "-", "/", "45/13/2024")
        );
    }

    static Stream<Arguments> findCases() {
        return Stream.of(
                Arguments.of("two-dates", "From 2024-01-02 to 2024-12-31", "-", List.of(List.of("2024", "01", "02"), List.of("2024", "12", "31"))),
                Arguments.of("none", "no dates here", "-", List.of()),
                Arguments.of("empty", "", "-", List.of()),
                Arguments.of("date-after-rejected", "2024-01-0234-05-06", "-", List.of(List.of("0234", "05", "06"))),
                Arguments.of("dot-separator", "2024x01x02 2024.01.02", ".", List.of(List.of("2024", "01", "02"))),
                Arguments.of("unicode-digits", "٢٠٢٤-٠١-٠٢ 2024-01-02", "-", List.of(List.of("2024", "01", "02")))
        );
    }

    @ParameterizedTest(name = "{0}")
    @MethodSource("cases")
    void reformatDates(String name, String text, String fromSep, String toSep, String want) {
        assertEquals(want, ReformatDates.reformatDates(text, fromSep, toSep), name);
    }

    @ParameterizedTest(name = "{0}")
    @MethodSource("findCases")
    void findDates(String name, String text, String sep, List<List<String>> want) {
        assertEquals(want, ReformatDates.findDates(text, sep), name);
    }
}
reformat_dates.cI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/find-and-replace-with-a-regular-expression/.

// POSIX regex.h compiles and matches a pattern, but it has no function to replace a match and no function to escape
// a literal string. This file has both.

#define _POSIX_C_SOURCE 200809L

#include "reformat_dates.h"

#include <regex.h>
#include <stdlib.h>
#include <string.h>

// A growing string.
struct buf {
    char *p;
    size_t n, cap;
};

static bool append(struct buf *b, const char *s, size_t len) {
    if (b->n + len + 1 > b->cap) {
        size_t cap = b->cap ? b->cap : 64;
        while (b->n + len + 1 > cap) {
            cap *= 2;
        }
        char *p = realloc(b->p, cap);
        if (p == nullptr) {
            return false;
        }
        b->p = p;
        b->cap = cap;
    }
    memcpy(b->p + b->n, s, len);
    b->n += len;
    b->p[b->n] = '\0';
    return true;
}

// Appends s to b with a backslash before each special character of an extended regular expression.
static bool append_escaped(struct buf *b, const char *s) {
    for (; *s != '\0'; s++) {
        if (strchr(".[\\()*+?{|^$", *s) != nullptr && !append(b, "\\", 1)) {
            return false;
        }
        if (!append(b, s, 1)) {
            return false;
        }
    }
    return true;
}

// Compiles the pattern of a date YYYY<sep>MM<sep>DD. ERE has no lookaround, so the pattern does not check the
// digits next to the date.
static bool date_pattern(regex_t *re, const char *sep) {
    struct buf b = {0};
    bool ok = append(&b, "([0-9]{4})", 10) && append_escaped(&b, sep) && append(&b, "([0-9]{2})", 10) &&
              append_escaped(&b, sep) && append(&b, "([0-9]{2})", 10);
    ok = ok && regcomp(re, b.p, REG_EXTENDED) == 0;
    free(b.p);
    return ok;
}

static bool is_digit_at(const char *text, size_t len, size_t i) {
    return i < len && text[i] >= '0' && text[i] <= '9';
}

// Finds the next date at or after *pos that has no digit next to it. On success, m holds offsets in text.
static bool next_date(const regex_t *re, const char *text, size_t len, size_t *pos, regmatch_t m[4]) {
    while (*pos < len) {
        if (regexec(re, text + *pos, 4, m, 0) != 0) {
            return false;
        }
        for (int i = 0; i < 4; i++) {
            m[i].rm_so += (regoff_t)*pos;
            m[i].rm_eo += (regoff_t)*pos;
        }
        size_t start = (size_t)m[0].rm_so;
        size_t end = (size_t)m[0].rm_eo;
        if ((start > 0 && is_digit_at(text, len, start - 1)) || is_digit_at(text, len, end)) {
            *pos = start + 1; // a date can start inside this match
            continue;
        }
        *pos = end;
        return true;
    }
    return false;
}

static bool append_group(struct buf *b, const char *text, regmatch_t g) {
    return append(b, text + g.rm_so, (size_t)(g.rm_eo - g.rm_so));
}

char *reformat_dates(const char *text, const char *from_sep, const char *to_sep) {
    regex_t re;
    if (!date_pattern(&re, from_sep)) {
        return nullptr;
    }
    size_t len = strlen(text);
    size_t sep_len = strlen(to_sep);
    struct buf out = {0};
    bool ok = append(&out, "", 0);
    size_t pos = 0;
    size_t last = 0;
    regmatch_t m[4];
    while (ok && next_date(&re, text, len, &pos, m)) {
        ok = append(&out, text + last, (size_t)m[0].rm_so - last) && append_group(&out, text, m[3]) &&
             append(&out, to_sep, sep_len) && append_group(&out, text, m[2]) && append(&out, to_sep, sep_len) &&
             append_group(&out, text, m[1]);
        last = (size_t)m[0].rm_eo;
    }
    ok = ok && append(&out, text + last, len - last);
    regfree(&re);
    if (!ok) {
        free(out.p);
        return nullptr;
    }
    return out.p;
}

int find_dates(const char *text, const char *sep, struct date **out, size_t *n) {
    regex_t re;
    if (!date_pattern(&re, sep)) {
        return -1;
    }
    size_t len = strlen(text);
    struct date *dates = nullptr;
    size_t count = 0;
    size_t pos = 0;
    regmatch_t m[4];
    while (next_date(&re, text, len, &pos, m)) {
        struct date *p = realloc(dates, (count + 1) * sizeof *p);
        if (p == nullptr) {
            free(dates);
            regfree(&re);
            return -1;
        }
        dates = p;
        struct date *d = &dates[count++];
        memcpy(d->year, text + m[1].rm_so, 4);
        d->year[4] = '\0';
        memcpy(d->month, text + m[2].rm_so, 2);
        d->month[2] = '\0';
        memcpy(d->day, text + m[3].rm_so, 2);
        d->day[2] = '\0';
    }
    regfree(&re);
    *out = dates;
    *n = count;
    return 0;
}
reformat_dates.h 23 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/find-and-replace-with-a-regular-expression/.

#ifndef REFORMAT_DATES_H
#define REFORMAT_DATES_H

#include <stddef.h>

struct date {
    char year[5];
    char month[3];
    char day[3];
};

// Returns a new string with each date YYYY<from_sep>MM<from_sep>DD in text changed to DD<to_sep>MM<to_sep>YYYY,
// or NULL if the pattern cannot be compiled or memory runs out. The caller frees the string.
char *reformat_dates(const char *text, const char *from_sep, const char *to_sep);

// Stores a new array with each date YYYY<sep>MM<sep>DD in text in *out, and its length in *n.
// Returns 0, or -1 on an error. The caller frees *out.
int find_dates(const char *text, const char *sep, struct date **out, size_t *n);

#endif
test_reformat_dates.c 92 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/find-and-replace-with-a-regular-expression/.

#include "reformat_dates.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct test_case {
    const char *name, *text, *from_sep, *to_sep, *want;
};

static const struct test_case cases[] = {
    {"one-date", "Due 2024-01-02.", "-", "/", "Due 02/01/2024."},
    {"two-dates", "From 2024-01-02 to 2024-12-31", "-", "/", "From 02/01/2024 to 31/12/2024"},
    {"no-date", "no dates here", "-", "/", "no dates here"},
    {"empty-text", "", "-", "/", ""},
    {"empty-to-sep", "2024-01-02", "-", "", "02012024"},
    {"whole-text", "2024-01-02", "-", "/", "02/01/2024"},
    {"adjacent", "2024-01-02,2024-01-03", "-", "/", "02/01/2024,03/01/2024"},
    {"digit-before", "12024-01-02", "-", "/", "12024-01-02"},
    {"digit-after", "2024-01-023", "-", "/", "2024-01-023"},
    {"date-after-rejected", "2024-01-0234-05-06", "-", "/", "2024-01-06/05/0234"},
    {"chained", "2024-01-02-03", "-", "/", "02/01/2024-03"},
    {"other-separator", "2024/01/02", "-", ".", "2024/01/02"},
    {"dot-separator", "2024x01x02 2024.01.02", ".", "-", "2024x01x02 02-01-2024"},
    {"backslash-separator", "2024\\01\\02", "\\", "-", "02-01-2024"},
    {"plus-separator", "2024+01+02 202401102", "+", "-", "02-01-2024 202401102"},
    {"dollar-in-replacement", "2024-01-02", "-", "$1", "02$101$12024"},
    {"backslash-in-replacement", "2024-01-02", "-", "\\1\\", "02\\1\\01\\1\\2024"},
    {"digit-in-replacement", "2024-01-02", "-", "0", "0200102024"},
    {"whole-match-in-replacement", "2024-01-02", "-", "$&", "02$&01$&2024"},
    {"unicode-digits", "٢٠٢٤-٠١-٠٢ and 2024-01-02 and 2024-01-02", "-", "/", "٢٠٢٤-٠١-٠٢ and 2024-01-02 and 02/01/2024"},
    {"non-ascii-text", "Café ☕ 2024-01-02 🙂", "-", "/", "Café ☕ 02/01/2024 🙂"},
    {"non-ascii-separator", "2024–01–02", "–", "·", "02·01·2024"},
    {"multiline", "2024-01-02\n2024-01-03\n", "-", "/", "02/01/2024\n03/01/2024\n"},
    {"not-a-calendar-date", "2024-13-45", "-", "/", "45/13/2024"},
};

// Each date is written as "year-month-day", and the dates are joined by spaces.
struct find_case {
    const char *name, *text, *sep, *want;
};

static const struct find_case find_cases[] = {
    {"two-dates", "From 2024-01-02 to 2024-12-31", "-", "2024-01-02 2024-12-31"},
    {"none", "no dates here", "-", ""},
    {"empty", "", "-", ""},
    {"date-after-rejected", "2024-01-0234-05-06", "-", "0234-05-06"},
    {"dot-separator", "2024x01x02 2024.01.02", ".", "2024-01-02"},
    {"unicode-digits", "٢٠٢٤-٠١-٠٢ 2024-01-02", "-", "2024-01-02"},
};

int main(void) {
    int failed = 0;
    for (size_t i = 0; i < sizeof cases / sizeof cases[0]; i++) {
        const struct test_case *c = &cases[i];
        char *got = reformat_dates(c->text, c->from_sep, c->to_sep);
        if (got == nullptr || strcmp(got, c->want) != 0) {
            fprintf(stderr, "FAIL %s: got \"%s\"\n", c->name, got ? got : "(null)");
            failed++;
        }
        free(got);
    }
    for (size_t i = 0; i < sizeof find_cases / sizeof find_cases[0]; i++) {
        const struct find_case *c = &find_cases[i];
        struct date *dates = nullptr;
        size_t n = 0;
        char got[256] = "";
        if (find_dates(c->text, c->sep, &dates, &n) != 0) {
            fprintf(stderr, "FAIL %s: error\n", c->name);
            failed++;
            continue;
        }
        for (size_t k = 0; k < n; k++) {
            size_t used = strlen(got);
            snprintf(got + used, sizeof got - used, "%s%s-%s-%s", k ? " " : "", dates[k].year, dates[k].month,
                     dates[k].day);
        }
        if (strcmp(got, c->want) != 0) {
            fprintf(stderr, "FAIL %s: got \"%s\"\n", c->name, got);
            failed++;
        }
        free(dates);
    }
    if (failed > 0) {
        return 1;
    }
    printf("ok\n");
    return 0;
}
ReformatDates.csI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/find-and-replace-with-a-regular-expression/.

using System.Text.RegularExpressions;

/// <summary>Finds dates with a regular expression and writes them in another order.</summary>
public static class ReformatDates
{
    /// <summary>Returns the pattern of a date YYYY(sep)MM(sep)DD with no digit next to it.</summary>
    public static Regex DatePattern(string sep)
    {
        // Regex.Escape makes each special character of sep match only itself.
        // [0-9] is ASCII only. \d also matches other decimal digits, such as ٢.
        string s = Regex.Escape(sep);
        return new Regex($"(?<![0-9])(?<year>[0-9]{{4}}){s}(?<month>[0-9]{{2}}){s}(?<day>[0-9]{{2}})(?![0-9])");
    }

    /// <summary>Changes each date YYYY(fromSep)MM(fromSep)DD in text to DD(toSep)MM(toSep)YYYY.</summary>
    public static string Reformat(string text, string fromSep, string toSep)
    {
        // In a replacement string, $ starts a substitution such as $1 or ${name}, and $$ is one $.
        string sep = toSep.Replace("$", "$$");
        return DatePattern(fromSep).Replace(text, "${day}" + sep + "${month}" + sep + "${year}");
    }

    /// <summary>Returns [year, month, day] for each date YYYY(sep)MM(sep)DD in text.</summary>
    public static List<string[]> FindDates(string text, string sep) =>
        DatePattern(sep).Matches(text)
            .Select(m => new[] { m.Groups["year"].Value, m.Groups["month"].Value, m.Groups["day"].Value })
            .ToList();
}
ReformatDatesTests.cs 62 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/find-and-replace-with-a-regular-expression/.

using Xunit;

public sealed class ReformatDatesTests
{
    public static TheoryData<string, string, string, string, string> Cases => new()
    {
        { "one-date", "Due 2024-01-02.", "-", "/", "Due 02/01/2024." },
        { "two-dates", "From 2024-01-02 to 2024-12-31", "-", "/", "From 02/01/2024 to 31/12/2024" },
        { "no-date", "no dates here", "-", "/", "no dates here" },
        { "empty-text", "", "-", "/", "" },
        { "empty-to-sep", "2024-01-02", "-", "", "02012024" },
        { "whole-text", "2024-01-02", "-", "/", "02/01/2024" },
        { "adjacent", "2024-01-02,2024-01-03", "-", "/", "02/01/2024,03/01/2024" },
        { "digit-before", "12024-01-02", "-", "/", "12024-01-02" },
        { "digit-after", "2024-01-023", "-", "/", "2024-01-023" },
        { "date-after-rejected", "2024-01-0234-05-06", "-", "/", "2024-01-06/05/0234" },
        { "chained", "2024-01-02-03", "-", "/", "02/01/2024-03" },
        { "other-separator", "2024/01/02", "-", ".", "2024/01/02" },
        { "dot-separator", "2024x01x02 2024.01.02", ".", "-", "2024x01x02 02-01-2024" },
        { "backslash-separator", "2024\\01\\02", "\\", "-", "02-01-2024" },
        { "plus-separator", "2024+01+02 202401102", "+", "-", "02-01-2024 202401102" },
        { "dollar-in-replacement", "2024-01-02", "-", "$1", "02$101$12024" },
        { "backslash-in-replacement", "2024-01-02", "-", "\\1\\", "02\\1\\01\\1\\2024" },
        { "digit-in-replacement", "2024-01-02", "-", "0", "0200102024" },
        { "whole-match-in-replacement", "2024-01-02", "-", "$&", "02$&01$&2024" },
        { "unicode-digits", "٢٠٢٤-٠١-٠٢ and 2024-01-02 and 2024-01-02", "-", "/", "٢٠٢٤-٠١-٠٢ and 2024-01-02 and 02/01/2024" },
        { "non-ascii-text", "Café ☕ 2024-01-02 🙂", "-", "/", "Café ☕ 02/01/2024 🙂" },
        { "non-ascii-separator", "2024–01–02", "–", "·", "02·01·2024" },
        { "multiline", "2024-01-02\n2024-01-03\n", "-", "/", "02/01/2024\n03/01/2024\n" },
        { "not-a-calendar-date", "2024-13-45", "-", "/", "45/13/2024" },
    };

    // Each date is written as "year-month-day", so that TheoryData can hold it.
    public static TheoryData<string, string, string, string[]> FindCases => new()
    {
        { "two-dates", "From 2024-01-02 to 2024-12-31", "-", ["2024-01-02", "2024-12-31"] },
        { "none", "no dates here", "-", [] },
        { "empty", "", "-", [] },
        { "date-after-rejected", "2024-01-0234-05-06", "-", ["0234-05-06"] },
        { "dot-separator", "2024x01x02 2024.01.02", ".", ["2024-01-02"] },
        { "unicode-digits", "٢٠٢٤-٠١-٠٢ 2024-01-02", "-", ["2024-01-02"] },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void Reformat(string name, string text, string fromSep, string toSep, string want)
    {
        Assert.False(string.IsNullOrEmpty(name));
        Assert.Equal(want, ReformatDates.Reformat(text, fromSep, toSep));
    }

    [Theory]
    [MemberData(nameof(FindCases))]
    public void FindDates(string name, string text, string sep, string[] want)
    {
        Assert.False(string.IsNullOrEmpty(name));
        Assert.Equal(want, ReformatDates.FindDates(text, sep).Select(d => string.Join("-", d)));
    }
}
reformatDates.jsI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/find-and-replace-with-a-regular-expression/.

/**
 * Returns the pattern of a date YYYY<sep>MM<sep>DD with no digit next to it.
 * @param {string} sep
 * @returns {RegExp}
 */
export function datePattern(sep) {
  // RegExp.escape makes each special character of sep match only itself.
  // The flag g finds all matches. The flag u reads the pattern as code points.
  const s = RegExp.escape(sep);
  return new RegExp(`(?<![0-9])(?<year>[0-9]{4})${s}(?<month>[0-9]{2})${s}(?<day>[0-9]{2})(?![0-9])`, "gu");
}

/**
 * Changes each date YYYY<fromSep>MM<fromSep>DD in text to DD<toSep>MM<toSep>YYYY.
 * @param {string} text
 * @param {string} fromSep
 * @param {string} toSep
 * @returns {string}
 */
export function reformatDates(text, fromSep, toSep) {
  // In a replacement string, $ starts a pattern such as $1, $& or $<name>, and $$ is one $.
  const sep = toSep.replaceAll("$", "$$$$");
  return text.replaceAll(datePattern(fromSep), `$<day>${sep}$<month>${sep}$<year>`);
}

/**
 * Returns [year, month, day] for each date YYYY<sep>MM<sep>DD in text.
 * @param {string} text
 * @param {string} sep
 * @returns {string[][]}
 */
export function findDates(text, sep) {
  return Array.from(text.matchAll(datePattern(sep)), (m) => [m.groups.year, m.groups.month, m.groups.day]);
}
reformatDates.test.js 55 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/find-and-replace-with-a-regular-expression/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { findDates, reformatDates } from "./reformatDates.js";

const cases = [
  ["one-date", "Due 2024-01-02.", "-", "/", "Due 02/01/2024."],
  ["two-dates", "From 2024-01-02 to 2024-12-31", "-", "/", "From 02/01/2024 to 31/12/2024"],
  ["no-date", "no dates here", "-", "/", "no dates here"],
  ["empty-text", "", "-", "/", ""],
  ["empty-to-sep", "2024-01-02", "-", "", "02012024"],
  ["whole-text", "2024-01-02", "-", "/", "02/01/2024"],
  ["adjacent", "2024-01-02,2024-01-03", "-", "/", "02/01/2024,03/01/2024"],
  ["digit-before", "12024-01-02", "-", "/", "12024-01-02"],
  ["digit-after", "2024-01-023", "-", "/", "2024-01-023"],
  ["date-after-rejected", "2024-01-0234-05-06", "-", "/", "2024-01-06/05/0234"],
  ["chained", "2024-01-02-03", "-", "/", "02/01/2024-03"],
  ["other-separator", "2024/01/02", "-", ".", "2024/01/02"],
  ["dot-separator", "2024x01x02 2024.01.02", ".", "-", "2024x01x02 02-01-2024"],
  ["backslash-separator", "2024\\01\\02", "\\", "-", "02-01-2024"],
  ["plus-separator", "2024+01+02 202401102", "+", "-", "02-01-2024 202401102"],
  ["dollar-in-replacement", "2024-01-02", "-", "$1", "02$101$12024"],
  ["backslash-in-replacement", "2024-01-02", "-", "\\1\\", "02\\1\\01\\1\\2024"],
  ["digit-in-replacement", "2024-01-02", "-", "0", "0200102024"],
  ["whole-match-in-replacement", "2024-01-02", "-", "$&", "02$&01$&2024"],
  ["unicode-digits", "٢٠٢٤-٠١-٠٢ and 2024-01-02 and 2024-01-02", "-", "/", "٢٠٢٤-٠١-٠٢ and 2024-01-02 and 02/01/2024"],
  ["non-ascii-text", "Café ☕ 2024-01-02 🙂", "-", "/", "Café ☕ 02/01/2024 🙂"],
  ["non-ascii-separator", "2024–01–02", "–", "·", "02·01·2024"],
  ["multiline", "2024-01-02\n2024-01-03\n", "-", "/", "02/01/2024\n03/01/2024\n"],
  ["not-a-calendar-date", "2024-13-45", "-", "/", "45/13/2024"],
];

const findCases = [
  ["two-dates", "From 2024-01-02 to 2024-12-31", "-", [["2024", "01", "02"], ["2024", "12", "31"]]],
  ["none", "no dates here", "-", []],
  ["empty", "", "-", []],
  ["date-after-rejected", "2024-01-0234-05-06", "-", [["0234", "05", "06"]]],
  ["dot-separator", "2024x01x02 2024.01.02", ".", [["2024", "01", "02"]]],
  ["unicode-digits", "٢٠٢٤-٠١-٠٢ 2024-01-02", "-", [["2024", "01", "02"]]],
];

for (const [name, text, fromSep, toSep, want] of cases) {
  test(`reformat ${name}`, () => {
    assert.equal(reformatDates(text, fromSep, toSep), want);
  });
}

for (const [name, text, sep, want] of findCases) {
  test(`find ${name}`, () => {
    assert.deepEqual(findDates(text, sep), want);
  });
}
reformatDates.tsI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/find-and-replace-with-a-regular-expression/.

/** Returns the pattern of a date YYYY<sep>MM<sep>DD with no digit next to it. */
export function datePattern(sep: string): RegExp {
  // RegExp.escape makes each special character of sep match only itself.
  // The flag g finds all matches. The flag u reads the pattern as code points.
  const s = RegExp.escape(sep);
  return new RegExp(`(?<![0-9])(?<year>[0-9]{4})${s}(?<month>[0-9]{2})${s}(?<day>[0-9]{2})(?![0-9])`, "gu");
}

/** Changes each date YYYY<fromSep>MM<fromSep>DD in text to DD<toSep>MM<toSep>YYYY. */
export function reformatDates(text: string, fromSep: string, toSep: string): string {
  // In a replacement string, $ starts a pattern such as $1, $& or $<name>, and $$ is one $.
  const sep = toSep.replaceAll("$", "$$$$");
  return text.replaceAll(datePattern(fromSep), `$<day>${sep}$<month>${sep}$<year>`);
}

/** Returns [year, month, day] for each date YYYY<sep>MM<sep>DD in text. */
export function findDates(text: string, sep: string): string[][] {
  return Array.from(text.matchAll(datePattern(sep)), (m) => {
    const { year, month, day } = m.groups as { year: string; month: string; day: string };
    return [year, month, day];
  });
}
reformatDates.test.ts 55 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/find-and-replace-with-a-regular-expression/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { findDates, reformatDates } from "./reformatDates.ts";

const cases: [string, string, string, string, string][] = [
  ["one-date", "Due 2024-01-02.", "-", "/", "Due 02/01/2024."],
  ["two-dates", "From 2024-01-02 to 2024-12-31", "-", "/", "From 02/01/2024 to 31/12/2024"],
  ["no-date", "no dates here", "-", "/", "no dates here"],
  ["empty-text", "", "-", "/", ""],
  ["empty-to-sep", "2024-01-02", "-", "", "02012024"],
  ["whole-text", "2024-01-02", "-", "/", "02/01/2024"],
  ["adjacent", "2024-01-02,2024-01-03", "-", "/", "02/01/2024,03/01/2024"],
  ["digit-before", "12024-01-02", "-", "/", "12024-01-02"],
  ["digit-after", "2024-01-023", "-", "/", "2024-01-023"],
  ["date-after-rejected", "2024-01-0234-05-06", "-", "/", "2024-01-06/05/0234"],
  ["chained", "2024-01-02-03", "-", "/", "02/01/2024-03"],
  ["other-separator", "2024/01/02", "-", ".", "2024/01/02"],
  ["dot-separator", "2024x01x02 2024.01.02", ".", "-", "2024x01x02 02-01-2024"],
  ["backslash-separator", "2024\\01\\02", "\\", "-", "02-01-2024"],
  ["plus-separator", "2024+01+02 202401102", "+", "-", "02-01-2024 202401102"],
  ["dollar-in-replacement", "2024-01-02", "-", "$1", "02$101$12024"],
  ["backslash-in-replacement", "2024-01-02", "-", "\\1\\", "02\\1\\01\\1\\2024"],
  ["digit-in-replacement", "2024-01-02", "-", "0", "0200102024"],
  ["whole-match-in-replacement", "2024-01-02", "-", "$&", "02$&01$&2024"],
  ["unicode-digits", "٢٠٢٤-٠١-٠٢ and 2024-01-02 and 2024-01-02", "-", "/", "٢٠٢٤-٠١-٠٢ and 2024-01-02 and 02/01/2024"],
  ["non-ascii-text", "Café ☕ 2024-01-02 🙂", "-", "/", "Café ☕ 02/01/2024 🙂"],
  ["non-ascii-separator", "2024–01–02", "–", "·", "02·01·2024"],
  ["multiline", "2024-01-02\n2024-01-03\n", "-", "/", "02/01/2024\n03/01/2024\n"],
  ["not-a-calendar-date", "2024-13-45", "-", "/", "45/13/2024"],
];

const findCases: [string, string, string, string[][]][] = [
  ["two-dates", "From 2024-01-02 to 2024-12-31", "-", [["2024", "01", "02"], ["2024", "12", "31"]]],
  ["none", "no dates here", "-", []],
  ["empty", "", "-", []],
  ["date-after-rejected", "2024-01-0234-05-06", "-", [["0234", "05", "06"]]],
  ["dot-separator", "2024x01x02 2024.01.02", ".", [["2024", "01", "02"]]],
  ["unicode-digits", "٢٠٢٤-٠١-٠٢ 2024-01-02", "-", [["2024", "01", "02"]]],
];

for (const [name, text, fromSep, toSep, want] of cases) {
  test(`reformat ${name}`, () => {
    assert.equal(reformatDates(text, fromSep, toSep), want);
  });
}

for (const [name, text, sep, want] of findCases) {
  test(`find ${name}`, () => {
    assert.deepEqual(findDates(text, sep), want);
  });
}
reformat_dates.goI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/find-and-replace-with-a-regular-expression/.

// Package reformatdates finds dates with a regular expression and writes them in another order.
package reformatdates

import (
	"regexp"
	"strings"
)

// datePattern returns the pattern of a date YYYY<sep>MM<sep>DD. RE2 has no
// lookaround, so the pattern does not check the digits next to the date.
func datePattern(sep string) *regexp.Regexp {
	// QuoteMeta makes each special character of sep match only itself.
	s := regexp.QuoteMeta(sep)
	return regexp.MustCompile(`(?P<year>[0-9]{4})` + s + `(?P<month>[0-9]{2})` + s + `(?P<day>[0-9]{2})`)
}

func isDigit(text string, i int) bool {
	return i >= 0 && i < len(text) && '0' <= text[i] && text[i] <= '9'
}

// eachDate calls f with the submatch indexes of each date in text that has no
// digit next to it. The indexes are offsets in text.
func eachDate(re *regexp.Regexp, text string, f func(m []int)) {
	for pos := 0; pos < len(text); {
		m := re.FindStringSubmatchIndex(text[pos:])
		if m == nil {
			return
		}
		for i := range m {
			m[i] += pos
		}
		if isDigit(text, m[0]-1) || isDigit(text, m[1]) {
			// A date can start inside this match, so search again one byte later.
			// m[0] is an ASCII digit, so m[0]+1 starts a character.
			pos = m[0] + 1
			continue
		}
		f(m)
		pos = m[1]
	}
}

// ReformatDates changes each date YYYY<fromSep>MM<fromSep>DD in text to
// DD<toSep>MM<toSep>YYYY.
func ReformatDates(text, fromSep, toSep string) string {
	re := datePattern(fromSep)
	// In a template, $ starts a reference such as $1 or ${name}, and $$ is one $.
	sep := strings.ReplaceAll(toSep, "$", "$$")
	template := "${day}" + sep + "${month}" + sep + "${year}"
	var out []byte
	last := 0
	eachDate(re, text, func(m []int) {
		out = append(out, text[last:m[0]]...)
		out = re.ExpandString(out, template, text, m)
		last = m[1]
	})
	return string(append(out, text[last:]...))
}

// FindDates returns [year, month, day] for each date YYYY<sep>MM<sep>DD in text.
func FindDates(text, sep string) [][]string {
	dates := [][]string{}
	eachDate(datePattern(sep), text, func(m []int) {
		dates = append(dates, []string{text[m[2]:m[3]], text[m[4]:m[5]], text[m[6]:m[7]]})
	})
	return dates
}
reformat_dates_test.go 63 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/find-and-replace-with-a-regular-expression/.

package reformatdates

import (
	"slices"
	"testing"
)

func TestReformatDates(t *testing.T) {
	cases := []struct{ name, text, fromSep, toSep, want string }{
		{"one-date", "Due 2024-01-02.", "-", "/", "Due 02/01/2024."},
		{"two-dates", "From 2024-01-02 to 2024-12-31", "-", "/", "From 02/01/2024 to 31/12/2024"},
		{"no-date", "no dates here", "-", "/", "no dates here"},
		{"empty-text", "", "-", "/", ""},
		{"empty-to-sep", "2024-01-02", "-", "", "02012024"},
		{"whole-text", "2024-01-02", "-", "/", "02/01/2024"},
		{"adjacent", "2024-01-02,2024-01-03", "-", "/", "02/01/2024,03/01/2024"},
		{"digit-before", "12024-01-02", "-", "/", "12024-01-02"},
		{"digit-after", "2024-01-023", "-", "/", "2024-01-023"},
		{"date-after-rejected", "2024-01-0234-05-06", "-", "/", "2024-01-06/05/0234"},
		{"chained", "2024-01-02-03", "-", "/", "02/01/2024-03"},
		{"other-separator", "2024/01/02", "-", ".", "2024/01/02"},
		{"dot-separator", "2024x01x02 2024.01.02", ".", "-", "2024x01x02 02-01-2024"},
		{"backslash-separator", "2024\\01\\02", "\\", "-", "02-01-2024"},
		{"plus-separator", "2024+01+02 202401102", "+", "-", "02-01-2024 202401102"},
		{"dollar-in-replacement", "2024-01-02", "-", "$1", "02$101$12024"},
		{"backslash-in-replacement", "2024-01-02", "-", "\\1\\", "02\\1\\01\\1\\2024"},
		{"digit-in-replacement", "2024-01-02", "-", "0", "0200102024"},
		{"whole-match-in-replacement", "2024-01-02", "-", "$&", "02$&01$&2024"},
		{"unicode-digits", "٢٠٢٤-٠١-٠٢ and 2024-01-02 and 2024-01-02", "-", "/", "٢٠٢٤-٠١-٠٢ and 2024-01-02 and 02/01/2024"},
		{"non-ascii-text", "Café ☕ 2024-01-02 🙂", "-", "/", "Café ☕ 02/01/2024 🙂"},
		{"non-ascii-separator", "2024–01–02", "–", "·", "02·01·2024"},
		{"multiline", "2024-01-02\n2024-01-03\n", "-", "/", "02/01/2024\n03/01/2024\n"},
		{"not-a-calendar-date", "2024-13-45", "-", "/", "45/13/2024"},
	}
	for _, c := range cases {
		if got := ReformatDates(c.text, c.fromSep, c.toSep); got != c.want {
			t.Errorf("%s: got %q, want %q", c.name, got, c.want)
		}
	}
}

func TestFindDates(t *testing.T) {
	cases := []struct {
		name, text, sep string
		want            [][]string
	}{
		{"two-dates", "From 2024-01-02 to 2024-12-31", "-", [][]string{{"2024", "01", "02"}, {"2024", "12", "31"}}},
		{"none", "no dates here", "-", [][]string{}},
		{"empty", "", "-", [][]string{}},
		{"date-after-rejected", "2024-01-0234-05-06", "-", [][]string{{"0234", "05", "06"}}},
		{"dot-separator", "2024x01x02 2024.01.02", ".", [][]string{{"2024", "01", "02"}}},
		{"unicode-digits", "٢٠٢٤-٠١-٠٢ 2024-01-02", "-", [][]string{{"2024", "01", "02"}}},
	}
	for _, c := range cases {
		got := FindDates(c.text, c.sep)
		if !slices.EqualFunc(got, c.want, slices.Equal) {
			t.Errorf("%s: got %q, want %q", c.name, got, c.want)
		}
	}
}
reformat_dates.shI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/find-and-replace-with-a-regular-expression/.

# _date_at TEXT I SEP tells if a date YYYY<SEP>MM<SEP>DD with no digit next to
# it starts at byte I of TEXT. The groups are then in BASH_REMATCH. The quoted
# "$3" in the pattern matches SEP as a literal string. ERE has no lookaround,
# so the code checks the digit before and the digit after.
_date_at() {
  local text=$1 i=$2
  ((i == 0)) || [[ ${text:i-1:1} != [0-9] ]] || return 1
  [[ ${text:i} =~ ^([0-9]{4})"$3"([0-9]{2})"$3"([0-9]{2}) ]] || return 1
  [[ ${text:i+${#BASH_REMATCH[0]}:1} != [0-9] ]]
}

# reformat_dates TEXT FROM_SEP TO_SEP prints TEXT with each date
# YYYY<FROM_SEP>MM<FROM_SEP>DD changed to DD<TO_SEP>MM<TO_SEP>YYYY, with no
# newline at the end.
reformat_dates() {
  # In the C locale, offsets count bytes and [0-9] is ASCII only.
  local LC_ALL=C
  local text=$1 from=$2 to=$3 out="" i=0
  while ((i < ${#text})); do
    if _date_at "$text" "$i" "$from"; then
      out+=${BASH_REMATCH[3]}$to${BASH_REMATCH[2]}$to${BASH_REMATCH[1]}
      ((i += ${#BASH_REMATCH[0]}))
    else
      out+=${text:i:1}
      ((i += 1))
    fi
  done
  printf '%s' "$out"
}

# find_dates TEXT SEP prints "YYYY MM DD" for each date YYYY<SEP>MM<SEP>DD in
# TEXT, one per line.
find_dates() {
  local LC_ALL=C
  local text=$1 sep=$2 i=0
  while ((i < ${#text})); do
    if _date_at "$text" "$i" "$sep"; then
      printf '%s %s %s\n' "${BASH_REMATCH[1]}" "${BASH_REMATCH[2]}" "${BASH_REMATCH[3]}"
      ((i += ${#BASH_REMATCH[0]}))
    else
      ((i += 1))
    fi
  done
}
test_reformat_dates.bats 163 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/find-and-replace-with-a-regular-expression/.

setup() {
  source "$BATS_TEST_DIRNAME/reformat_dates.sh"
}

@test "reformat one-date" {
  got=$(reformat_dates $'Due 2024-01-02.' $'-' $'/'; printf .)
  [ "$got" = $'Due 02/01/2024.'. ]
}

@test "reformat two-dates" {
  got=$(reformat_dates $'From 2024-01-02 to 2024-12-31' $'-' $'/'; printf .)
  [ "$got" = $'From 02/01/2024 to 31/12/2024'. ]
}

@test "reformat no-date" {
  got=$(reformat_dates $'no dates here' $'-' $'/'; printf .)
  [ "$got" = $'no dates here'. ]
}

@test "reformat empty-text" {
  got=$(reformat_dates $'' $'-' $'/'; printf .)
  [ "$got" = $''. ]
}

@test "reformat empty-to-sep" {
  got=$(reformat_dates $'2024-01-02' $'-' $''; printf .)
  [ "$got" = $'02012024'. ]
}

@test "reformat whole-text" {
  got=$(reformat_dates $'2024-01-02' $'-' $'/'; printf .)
  [ "$got" = $'02/01/2024'. ]
}

@test "reformat adjacent" {
  got=$(reformat_dates $'2024-01-02,2024-01-03' $'-' $'/'; printf .)
  [ "$got" = $'02/01/2024,03/01/2024'. ]
}

@test "reformat digit-before" {
  got=$(reformat_dates $'12024-01-02' $'-' $'/'; printf .)
  [ "$got" = $'12024-01-02'. ]
}

@test "reformat digit-after" {
  got=$(reformat_dates $'2024-01-023' $'-' $'/'; printf .)
  [ "$got" = $'2024-01-023'. ]
}

@test "reformat date-after-rejected" {
  got=$(reformat_dates $'2024-01-0234-05-06' $'-' $'/'; printf .)
  [ "$got" = $'2024-01-06/05/0234'. ]
}

@test "reformat chained" {
  got=$(reformat_dates $'2024-01-02-03' $'-' $'/'; printf .)
  [ "$got" = $'02/01/2024-03'. ]
}

@test "reformat other-separator" {
  got=$(reformat_dates $'2024/01/02' $'-' $'.'; printf .)
  [ "$got" = $'2024/01/02'. ]
}

@test "reformat dot-separator" {
  got=$(reformat_dates $'2024x01x02 2024.01.02' $'.' $'-'; printf .)
  [ "$got" = $'2024x01x02 02-01-2024'. ]
}

@test "reformat backslash-separator" {
  got=$(reformat_dates $'2024\\01\\02' $'\\' $'-'; printf .)
  [ "$got" = $'02-01-2024'. ]
}

@test "reformat plus-separator" {
  got=$(reformat_dates $'2024+01+02 202401102' $'+' $'-'; printf .)
  [ "$got" = $'02-01-2024 202401102'. ]
}

@test "reformat dollar-in-replacement" {
  got=$(reformat_dates $'2024-01-02' $'-' $'$1'; printf .)
  [ "$got" = $'02$101$12024'. ]
}

@test "reformat backslash-in-replacement" {
  got=$(reformat_dates $'2024-01-02' $'-' $'\\1\\'; printf .)
  [ "$got" = $'02\\1\\01\\1\\2024'. ]
}

@test "reformat digit-in-replacement" {
  got=$(reformat_dates $'2024-01-02' $'-' $'0'; printf .)
  [ "$got" = $'0200102024'. ]
}

@test "reformat whole-match-in-replacement" {
  got=$(reformat_dates $'2024-01-02' $'-' $'$&'; printf .)
  [ "$got" = $'02$&01$&2024'. ]
}

@test "reformat unicode-digits" {
  got=$(reformat_dates $'٢٠٢٤-٠١-٠٢ and 2024-01-02 and 2024-01-02' $'-' $'/'; printf .)
  [ "$got" = $'٢٠٢٤-٠١-٠٢ and 2024-01-02 and 02/01/2024'. ]
}

@test "reformat non-ascii-text" {
  got=$(reformat_dates $'Café ☕ 2024-01-02 🙂' $'-' $'/'; printf .)
  [ "$got" = $'Café ☕ 02/01/2024 🙂'. ]
}

@test "reformat non-ascii-separator" {
  got=$(reformat_dates $'2024–01–02' $'–' $'·'; printf .)
  [ "$got" = $'02·01·2024'. ]
}

@test "reformat multiline" {
  got=$(reformat_dates $'2024-01-02\n2024-01-03\n' $'-' $'/'; printf .)
  [ "$got" = $'02/01/2024\n03/01/2024\n'. ]
}

@test "reformat not-a-calendar-date" {
  got=$(reformat_dates $'2024-13-45' $'-' $'/'; printf .)
  [ "$got" = $'45/13/2024'. ]
}

@test "find two-dates" {
  got=$(find_dates $'From 2024-01-02 to 2024-12-31' $'-')
  [ "$got" = $'2024 01 02\n2024 12 31' ]
}

@test "find none" {
  got=$(find_dates $'no dates here' $'-')
  [ "$got" = $'' ]
}

@test "find empty" {
  got=$(find_dates $'' $'-')
  [ "$got" = $'' ]
}

@test "find date-after-rejected" {
  got=$(find_dates $'2024-01-0234-05-06' $'-')
  [ "$got" = $'0234 05 06' ]
}

@test "find dot-separator" {
  got=$(find_dates $'2024x01x02 2024.01.02' $'.')
  [ "$got" = $'2024 01 02' ]
}

@test "find unicode-digits" {
  got=$(find_dates $'٢٠٢٤-٠١-٠٢ 2024-01-02' $'-')
  [ "$got" = $'2024 01 02' ]
}

@test "the locale stays the same" {
  LC_ALL=C.UTF-8
  reformat_dates "2024-01-02" "-" "/" >/dev/null
  [ "$LC_ALL" = C.UTF-8 ]
}

References

  1. The Python Standard Library, re, Regular Expression Syntax: \d, (?P<name>...), (?<!...), (?!...), possessive quantifiers; Flags: re.ASCII; Functions: re.match, re.fullmatch, re.sub (\g<name>), re.escape; search() vs. match()
  2. MDN Web Docs, String.prototype.replace(), Specifying a string as the replacement
  3. MDN Web Docs, String.prototype.replaceAll(), Exceptions
  4. MDN Web Docs, RegExp.escape(), Description
  5. MDN Web Docs, RegExp.prototype.test(), Description, lastIndex with the global flag
  6. MDN Web Docs, Character class escape, Description, \d
  7. Java SE 25 API, java.util.regex.Pattern, Predefined character classes (\d); Groups and capturing, named groups; quote(String); UNICODE_CHARACTER_CLASS
  8. Java SE 25 API, java.util.regex.Matcher, appendReplacement(StringBuilder, String); replaceAll(Function); results(); quoteReplacement(String)
  9. .NET API reference, Regex.Escape, Remarks
  10. .NET, Substitutions in regular expressions, the table of substitutions; Substituting a "$" Character
  11. .NET, Grouping constructs in regular expressions, Named matched subexpressions; Zero-width negative lookbehind assertions
  12. .NET, Character classes in regular expressions, Decimal digit character: \d
  13. .NET, Regular expression options, the table of options, NonBacktracking
  14. .NET, Backtracking in regular expressions, Backtracking with nested optional quantifiers; Specify a time-out interval
  15. Go standard library, regexp, Overview (linear time); func QuoteMeta; func (*Regexp) Expand; func (*Regexp) FindStringSubmatchIndex
  16. Go standard library, regexp/syntax, Overview: Grouping ((?P<name>re), (?<name>re)); Perl character classes (\d)
  17. The regex crate 1.13.1 for Rust, Overview (no look-around, worst case O(m * n)); Perl character classes (\d is \p{Nd})
  18. The regex crate 1.13.1, struct Regex, captures_at; replace (the replacement string, $$, NoExpand)
  19. The regex crate 1.13.1, fn escape, Description
  20. cppreference.com, Modified ECMAScript regular expression grammar, Assertions
  21. cppreference.com, Regular expressions library, Regular expression grammars (the default); Algorithms (regex_match, regex_search, regex_replace)
  22. The Open Group Base Specifications Issue 8, regcomp, regexec, regerror, regfree, DESCRIPTION (REG_EXTENDED, regmatch_t, rm_so and rm_eo)
  23. The Open Group Base Specifications Issue 8, Base Definitions, Regular Expressions, 9.4.2 ERE Ordinary Characters; 9.4.3 ERE Special Characters
  24. GNU Bash Reference Manual, 3.2.5.2 Conditional Constructs, [[ ... ]] and the =~ operator; 5.2 Bash Variables, BASH_REMATCH

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (bash)I0 not checked yet
  • the tests did not run in this build
Code (c)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (cpp)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (csharp)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (go)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (java)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (javascript)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (python)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (typescript)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source

The native tests pass in 8 of 9 languages in this build.