Skip to content

^ in an alternation group silently fails to match (e.g. (a|b|^)x, (^|[^0-9])x), while GNU grep matches #573

Open

Description

@gorloffslava

ugrep 7.8.5 (the v7.8.5 tag built from source, ./configure && make, gcc 14, aarch64 Linux) returns no match for some
regexes whose group has ^ as one alternative, where GNU grep 3.x matches. There is no error or warning; the count is
just wrong. The $ anchor in the same positions works.

Reproduction:

printf 'fail 1\nx; fail 2\nfoo\n' > input.txt
printf '5798-72bbf60eb5b8.json\n' > input2.txt

ugrep -cE '(^|a|b)fail' input.txt      # 1  (GNU grep: 1)
ugrep -cE '(a|^|b)fail' input.txt      # 1  (GNU grep: 1)
ugrep -cE '(a|b|^)fail' input.txt      # 0  (GNU grep: 1)   <- ^ as the third alternative
ugrep -cE '(a|b|c|^)fail' input.txt    # 0  (GNU grep: 1)
ugrep -cE '(a|b|^|c)fail' input.txt    # 0  (GNU grep: 1)
ugrep -cE '(;|&&|^)fail' input.txt     # 0  (GNU grep: 1)

ugrep -cE '(^|x)5798' input2.txt       # 1  (GNU grep: 1)
ugrep -cE '(^|[^0-9])5798' input2.txt  # 0  (GNU grep: 1)   <- ^ first, but the other alternative is a bracket class
ugrep -cE '([^0-9]|^)5798' input2.txt  # 0  (GNU grep: 1)

printf 'x fail\nfail\n' > input3.txt
ugrep -cE 'fail(a|b|$)' input3.txt     # 2  (GNU grep: 2)   <- $ is fine in every position tried

The same results come from ugrep 7.8.4. As far as I can tell, ^ placed third or later in a group never matches, and
^ in first or second place fails when another alternative is a bracket expression. In both cases the line-start
alternative is dropped with no diagnostic.

Why it matters: patterns like (^|[^0-9])N([^0-9]|$) and (^|;|&&)cmd are common idioms for "N as a whole token" and
"cmd at the start of a statement". With ugrep they silently undercount. We found it because a count we had recorded was
wrong for weeks: it was always taken with ugrep and was off by exactly the line-initial matches.

Expected: the same matches as GNU grep (POSIX ERE: ^ is an anchor in any alternative), or an error like the one #427
used to raise, rather than a silent miss.

(Found while auditing shell commands an AI coding assistant had run; the reproduction above was checked by hand
against standalone builds of ugrep and GNU grep.)

Activity

  1. gorloffslava commented on Oct 13, 2026

    @gorloffslava
    Author

    A follow-up with a diagnosis. It was prepared with an AI coding assistant: the analysis, the experiments behind it and this text. I am not sending a patch or any code, because CONTRIBUTING.md does not permit contributions sourced from AI tools, so the fix is yours to write. Every number below comes from a command run against the v7.8.5 tag (f2cc252c01) and GNU grep 3.11, built and run in the gcc:14 image on aarch64 Linux.

    In the shell comments, "parse2() change" and "both changes" name a local experiment that removed the causes described below. It was only used to check the diagnosis, and it is described here in words only.

    There seem to be two independent causes, both in lib/pattern.cpp. That file is byte-identical in RE/flex 6.5.

    1. Pattern::parse2(): an anchor-only alternative keeps the previous alternative's state

    • Pattern::parse1() declares its per-alternative state (firstpos1, lastpos1, nullable1, lazypos1 and iter1) once, before its loop over |, and passes it to parse2() for every alternative after the first. Pattern::parse() does the same with its own locals for the top-level alternatives.
    • That state is reset in parse4(). parse2() reaches parse3() and parse4() only when something follows the leading anchors, so for an alternative that is just ^ nothing resets it.
    • From the third alternative of a group on, the state still holds the previous alternative's positions. ^ then never becomes a first position and is attached after the previous alternative instead: (a|b|^)fail acts like (a|b|b^)fail.
    • On the second alternative of a group the positions are still empty, which is why (a|^|b)fail works. nullable1 and iter1 are read uninitialized there.
    • At the top level the second position already fails when the alternative before it is a regex rather than a plain string. Plain strings take a different path, which is why zz|^ agrees with GNU grep under -Y (without -Y, ugrep's documented empty-match default applies):
    printf 'hello\nab\n\nz\n' | ugrep -c -e 'a.' -e '^'     # 7.8.5: 1, parse2() change: 4, GNU grep -cE: 4
    printf 'hello\nab\n\nz\n' | ugrep -cE 'a.|^|z$'        # 7.8.5: 2, parse2() change: 4, GNU grep -cE: 4
    • The same stale state reaches an empty alternative in a group that is not at the start of the pattern, when RE/flex's Pattern is used directly: x(a|)y and x(a|b|)y both miss xy. ugrep's converter rejects empty alternatives with "empty (sub)expression", so ugrep itself does not reach this. A small driver over RE/flex's Pattern checked 8 such shapes: 7 of them were wrong before, and all 8 were right with both changes.

    2. Pattern::analyze_dfa(): the final cut keeps too few lookback characters

    • The match predictor cuts the DFA and records the characters on the edges before the cut, so that find() can step back from a predicted position to the start of a match. The search branch saves the accumulated set, cut_chars.
    • The branch commented "save final best metrics when last character matters" saves only chars, the characters since the last cut. It was added in d6ae4bd ("optimize 2nd type of pattern Two regular expressions with poor performance #485") and first released in v7.4.2.
    • For (^|[^0-9])5798 without -U, that branch wins (best: depth=1/3 in the DEBUG log) and the lookback set is 7 9 80..bf. There is no 5 in it, so find() never steps back to the start of the match, although scan() at column 0 matches. With -U the predictor takes a shallower cut, which is why -U hides the defect.
    • It is not specific to anchors:
    printf 'abcdefghij\nx abcdefghij\n' | ugrep -c '[^a]?abcd'      # 7.8.5: 0, parse2() change: 0, both changes: 2, GNU grep -cE: 2
    printf '5798\nx5798\na 5798\n' | ugrep -c '[^0-9]?5798'          # 7.8.5: 0, parse2() change: 0, both changes: 3, GNU grep -cE: 3
    printf '5798\nx5798\nqAAA5798\nzz qAAA5798 zz\n' | ugrep -U -c '(^|x|q[A-\x7f][A-\x7f][A-\x7f])5798'   # 7.8.5: 0, both changes: 4, GNU grep -cE: 4

    GNU grep reads \x7f inside a bracket as the characters \, x, 7 and f. The count is the same under both readings.

    Results of the experiment

    • The 12 patterns of this issue: its 10 commands, plus fail(a|$|b) and fail($|a|b). 7.8.5 disagrees with GNU grep on 6 of them, the parse2() change alone on 2, and both changes on none.
    • make test: ALL TESTS PASSED, single- and multi-threaded, before and after.
    • A differential test against GNU grep -nE. It compared the matching line numbers and the exit code over 474 generated patterns, each with no flag, -w, -x and -i, under LC_ALL=C.UTF-8: 1896 cases.
      • 7.8.5 agrees on 781 cases and both changes on 1426.
      • No case among these 1896 that agreed before disagrees after.
      • Line by line, 10 lines do. All are a trailing \b before a non-ASCII letter, which 7.8.5 already treats differently from GNU grep: fail\b matches failé. 2 of the 10 first appear with the parse2() change and 8 with the analyze_dfa() change.
    • A second, independently generated set of 402 patterns, compared on the matched text (-on):
      • 1608 cases in UTF-8 mode: 1486 agree before, 1533 after.
      • 804 cases with -U, against GNU grep under LC_ALL=C: 789 before, 796 after.
      • Again, no case in this set got worse. One case, -w '[^[:alpha:]]*Finn', gained 5 differing lines. ugrep's [[:alpha:]] does not match 本 while GNU grep's does, and 7.8.5 already prints 本Finn for -w '[^[:alpha:]]Finn'.

    Caveat: the parse2() change alone exposes a third, older defect

    None of the measured sets contained this shape. Once ^ works as an alternative, a pattern such as H.llo|^ can match empty at the start of a line, and lines are lost that 7.8.5 counted correctly:

    printf 'foo Hello\n' | ugrep -c 'H.llo|^'                              # 7.8.5: 1, parse2() change: 0, both changes: 0, GNU grep -cE: 1
    printf 'foo Hello\nHello\nx Hello x\n' | ugrep -c '(H.llo|W.rld|^)'    # 7.8.5: 3, parse2() change: 1, both changes: 1, GNU grep -cE: 3

    The same loss is already in 7.8.5 wherever its ^ is not dropped:

    printf 'foo Hello\n' | ugrep -c '(H.llo|^)'                            # 7.8.5: 0, GNU grep -cE: 1
    printf 'foo Hello\n' | ugrep -c '(^|H.llo)'                            # 7.8.5: 0, GNU grep -cE: 1
    printf 'one\n' | ugrep -cY '(^|H.llo)'                                 # 7.8.5: 0, GNU grep -cE: 1

    Measured: for each failing shape, the predictor printed by a small driver over RE/flex's Pattern reports min=3, cut=3 and an unbounded lookback. The control H.llo|x* reports min=0 and no cut, and it keeps its lines.

    Inferred from reading the code, not traced:

    • analyze_dfa() skips the cut only when the start state itself accepts. Here the start state accepts only through the ^ meta edge, so the DFA is still cut.
    • When Matcher::match() then rejects the empty match at the start of the line, it advances with the predictor and does not look back. Its comment says that is safe because "we can't make a DFA cut for empty-matching patterns". A match that starts before the predicted position is then skipped.
    • With -Y, the same cut makes the search skip lines whose only match is the empty one.

    In the shapes we measured, the loss needs the other alternatives to be long enough for the predictor to cut the DFA. When something follows the group, as in (H.llo|W.rld|^)x, the parse2() change gives GNU grep's result, and (Hel+o|Wor+ld|^) loses nothing.

    So for the X|^ and (X|Y|^) shapes, the parse2() fix needs a companion: either no cut when the pattern can match empty after an anchor, or a lookback in that branch. We have not tried either.

    Cost of the analyze_dfa() change (indicative)

    The test text was 100 MB: six copies of the text and source files of the ugrep and RE/flex repositories. Timings are the minimum CPU time of 5 runs of single-threaded ugrep -J1 -cE on a loaded aarch64 machine.

    • Where the change alters the lookback set, CPU time grew 4.6x to 8.7x:
      • [^a]?abcd: 0.19 s → 1.33 s
      • [a-q][^e]{7}x: 0.13 s → 1.16 s
      • [^a]{9}the: 0.77 s → 3.53 s
    • Two regular expressions with poor performance #485's own [a-q][^u-z]{13}x, and the control \w+ing, were not slower.
    • How often the lookback set changes: in the 474-pattern differential set above, for 134 of the 368 patterns that reach the engine (the converter rejects the others), all without -U; for none with -U.
    • What 7.8.5 misses on the same text:
      • [^a]{9}the: 9450 lines, where GNU grep -acE and the experiment count 55374.
      • [^A-Z]{1,3}the: 21216, where they count 78420.
      • With -U, [a-q][^e]{7}x: 19170, where they count 23346.
      • (-a because the text holds NUL bytes.)

    Also noticed (present in 7.8.5, separate from the above)

    • A lone anchor escape as an alternative is rejected with "empty (sub)expression": (x|\b)cat, (x|\B)cat, (x|\<)cat, (x|\>)cat and (x|\A)cat. The (^|x) causes error "empty expression" #427 change lifted this for ^ only.
    • ^ followed by a group that starts with \b can miss at column 0:
    printf 'xfail\n' | ugrep -c '^(\bx|^)fail'      # 7.8.5: 0, GNU grep -cE: 1
    printf 'éfail\n' | ugrep -c '^(\béfail)'        # 7.8.5: 0, GNU grep -cE: 1
    • A ^ that follows other characters matches in ugrep, where GNU grep treats it as an anchor that cannot match there:
    printf 'xfail\n' | ugrep -c 'x^fail'            # 7.8.5: 1, GNU grep -cE: 0
    printf 'xc\nxac\nxbc\n' | ugrep -cE 'x(a|b|^)c'  # 7.8.5: 3, GNU grep -cE: 2
  2. exGeni commented on Nov 13, 2026

    @exGeni

    Status check against v7.8.5 (f2cc252, which is also current master), plus a few data points that may help narrow this down. This comment was written by an AI coding agent on behalf of its owner. I am not sending a patch or code, because CONTRIBUTING.md does not permit contents sourced from AI tools.

    Still reproduces on x86_64 Linux (the report used aarch64). gcc 12.2, v7.8.4 and v7.8.5 built from the tag tarballs, configured without PCRE2, compared with GNU grep 3.8:

    printf 'a src/x\n'  | ugrep -cE '(^|[^b])src/'     # 0  (GNU grep: 1)
    printf 'a abcd x\n' | ugrep -cE '(^|[^b])abcd'     # 0  (GNU grep: 1)
    printf 'a abcde x\n' | ugrep -cE '(^|[^b])abcde'   # 1  (GNU grep: 1)

    What triggers it, in the (^|[^b])LIT family. With LIT the first n letters of the alphabet (n = 1 to 24), only n = 4 fails. The reporter's (^|[^0-9])5798 has a 4-byte literal too. Tried and missed, on a line like a LIT x: src/, lib/, test, path, node, \.git, 5798, foo-, and éé (4 bytes in UTF-8). ééé (6 bytes) matches. With -U the 4-byte literal matches; -i did not help on these inputs.

    When it started, for these patterns. Building one commit at a time, 402e897 (the parent of d6ae4bd) matches both src/ and abcd above (count 1), while d6ae4bd and 9acd876 do not. By release: 7.0.0 and 7.4.1 match; 7.4.2, 7.5.0, 7.7.0, 7.8.4 and 7.8.5 do not.

    Cause 2 of the earlier comment. It fits what I see: a local experiment on the final-cut branch of analyze_dfa() makes src/, abcd and (^|[^0-9])5798 match (abcde matched before it). I did not run make test, timings, or anything for the parse2() cause on it.

    Downstream. In Claude Code 2.1.309 the Bash tool's grep is a shell function that starts the bundled binary as ugrep. As of 2026-11-13, the npm latest (2.1.325) and stable (2.1.311) linux-x64 binaries, run with argv0 ugrep, print ugrep 7.8.4 and give 0 for (^|[^b])src/ on a src/x. The same pattern shape is reported at anthropics/claude-code#98421 and #101399 (both open).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions