Repository navigation
Description
In a -P pattern, \K resets the start of the reported match, but the match itself still
starts where the pattern began. GNU grep applies the -w (whole word) and -x (whole line) tests
to the whole match. uu_grep applies them to the reported part after \K, so
grep -wP 'foo\Kbar' rejects foobar, grep -xP 'key=\K.*' can never select anything, and
grep -wP 'foo \Kbar' wrongly accepts xfoo bar. Without -w/-x the two agree
(grep -oP 'foo\Kbar' prints bar in both).
Reproduction
Rust (incorrect)
$ printf 'foobar\n' | ./target/release/grep -wP 'foo\Kbar'
# Exit code: 1
$ printf 'key=value\n' | ./target/release/grep -xP 'key=\K.*'
# Exit code: 1
$ printf 'xfoo bar\n' | ./target/release/grep -wP 'foo \Kbar'
xfoo bar
# Exit code: 0GNU (correct)
$ printf 'foobar\n' | LC_ALL=C /usr/bin/grep -wP 'foo\Kbar'
foobar
# Exit code: 0
$ printf 'key=value\n' | LC_ALL=C /usr/bin/grep -xP 'key=\K.*'
key=value
# Exit code: 0
$ printf 'xfoo bar\n' | LC_ALL=C /usr/bin/grep -wP 'foo \Kbar'
# Exit code: 1Root cause
CompiledPattern::search_leftmost (src/matcher.rs:354) throws away the value returned by
Oniguruma's search, which is the position where the match began, and returns only group 0 of the
region, whose start \K has moved forward:
fn search_leftmost(&self, line: &[u8], offset: usize) -> Option<(usize, usize)> {
let mut region = Region::new();
self.leftmost.search(line, offset, Some(&mut region))?;
region.pos(0)
}Matcher::match_line then runs the -x check (start == 0, src/matcher.rs:72) and
is_word_match(line, start, end) (src/matcher.rs:76) on that trimmed start.
Test
#[test]
fn perl_keep_with_word_and_line_regexp() {
let (_s, mut c) = ucmd();
c.args(&["-wP", r"foo\Kbar"])
.pipe_in("foobar\n")
.succeeds()
.stdout_only("foobar\n");
let (_s, mut c) = ucmd();
c.args(&["-xP", r"key=\K.*"])
.pipe_in("key=value\n")
.succeeds()
.stdout_only("key=value\n");
let (_s, mut c) = ucmd();
c.args(&["-wP", r"foo \Kbar"])
.pipe_in("xfoo bar\n")
.fails_with_code(1)
.no_output();
}Reported by Anthropic's OSS Scanner (ANT-2026-3CV8NSKJ).
Activity