Skip to content

Matching

Mikhail Deynekin edited this page Oct 12, 2026 · 2 revisions

Совпадение и регулярные выражения

Matching

Matching

Four pattern kinds, selected by a flag (literal is the default):

(default) literal text. . is a dot, ( is a parenthesis. Escape sequences \n \t \r \0 \xNN are interpreted, so sr replace 'a\tb' 'a b' matches a real tab. The replacement is inserted verbatim — $1, \1 and & stay literal, which makes config files safe to edit. Use --no-escapes to disable escape processing.

--regex Python regular expressions. The replacement is a template: \1, \g, \n and \ work as in re.sub. sr replace 'version = "(\d+)"' 'version = "\1.dev0"' --regex

--ere POSIX Extended Regular Expressions (grep -E / sed -E syntax), translated to Python: :digit:, <, > and {m,n} work. Useful for patterns copied from shell scripts. sr replace [[:digit:]]{4}-:digit:{4}' 'XXXX-XXXX' --ere

--pcre Perl syntax: \A, \z, (?...), atomic groups and possessive quantifiers (Python 3.11+). sr replace '(?<=user=)[^&]+' 'admin' --pcre

Modifiers (they apply to every kind):

-i, --ignore-case case-insensitive -w, --word-boundary whole words only (wraps the pattern in \b) -m, --multiline the pattern may span lines ('.' matches newline) -L, --line-range R restrict edits to lines R (10, 10-20, 10-, -20) -M, --max-count N at most N replacements per file --no-global only the first occurrence on each line --context N context lines in previews and diffs (default 3)

Counting rules

matches counts occurrences, not lines: a line with three hits counts three. That is what the summary reports and what --max-count limits. Matches outside --line-range are reported separately and never replaced.

Because one engine does both the counting and the replacing, -i and -w cannot disagree between the two — a class of bug that made the reported number of replacements wrong in grep+sed based tools.

Escaping cheat sheet

literal dot sr replace "1.2.3" "1.2.4" regex dot sr replace '1.2.3' '1.2.4' --regex literal backslash sr replace 'C:\temp' 'D:\data' --no-escapes newline in the pattern sr replace 'a\nb' 'a b' --multiline tab sr replace '\t' ' ' hex byte sr replace '\x00' '' --binary


Страница сгенерирована из встроенной справки sr 7.0.1 (sr help <topic>). Первоисточник — sr/help_system.py; он же питает man sr и sr help --all. Если страница и вывод sr help расходятся, верить нужно sr help: он всегда соответствует установленной версии.

Clone this wiki locally