Skip to content

\B matches between the bytes of a UTF-8 character #677

Open

Description

@robertmorelli

issue:
\B treats the bytes of a multi-byte character as separate non-word characters, so an empty match lands inside é. Go's regexp reports offset 3.

repro:

#include <re2/re2.h>
#include <cstdio>
int main() {
  re2::StringPiece in("a\u00E9"), m;   // 3 bytes
  RE2("\\B").Match(in, 0, in.size(), RE2::UNANCHORED, &m, 1);
  printf("%td\n", m.data() - in.data());   // 2
}

expected:
prints 3

system:
RE2 2025-11-05 (Homebrew)
macOS 27.0 (build 26A428), arm64

Activity

  1. xili-ytl commented on Oct 27, 2026

    @xili-ytl

    Hi RE2 maintainers,

    I'd like to investigate #677 and agree on the intended behavior before developing a fix.

    I built unmodified RE2 at 2da0056 with C++17 on Linux x86_64. For UTF-8 input aé (bytes 61 c3 a9), an unanchored \B matches at byte offset 2, inside the character. Three- and four-byte UTF-8 examples also select offset 2. NFA, BitState and forward/reverse DFA search agree; an anchored OnePass search accepts the same interior position.

    The behavior also affects rewriting:

    std::string s = "a\xc3\xa9";
    RE2::GlobalReplace(&s, RE2("\\B"), "_");
    // Actual bytes: 61 c3 5f a9 5f (invalid UTF-8)

    Two compatibility cases matter when choosing a fix: Latin-1 mode legitimately accepts byte offset 2, and \C\B\C currently matches both bytes of UTF-8 é. Input 61 80 80 also accepts offset 2, so rejecting every continuation-byte value would change malformed-input behavior as well.

    Should ordinary UTF-8 searches restrict these match positions to code-point boundaries while retaining explicit byte-pattern behavior? What contract should apply to malformed UTF-8 and a caller-supplied start position inside a character? ASCII-only word classification can remain unchanged.

    Depending on that contract, the choices appear to be a compiler/empty-width constraint shared by all engines, or a restriction on eligible UTF-8 search starts. The former needs corresponding DFA byte classes/reverse-state handling; the latter needs care to preserve linear-time search and explicit \C behavior. I would add native regression cases for the agreed semantics, all affected engines and Latin-1/byte-pattern controls, then run the full test suite and relevant benchmarks.

    Which direction would you prefer?

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