# OfficeCLI Find and Replace Regex: Complete Guide to Pattern Matching

> Master OfficeCLI find and replace with regex. Learn how to use raw-string prefixes for global RegExp matching and pattern detection. Securely process up to 500 matches.

- Repository: [OfficeAI/OfficeCLI](https://github.com/iofficeai/OfficeCLI)
- Tags: how-to-guide
- Published: 2026-08-08

---

**OfficeCLI supports regex-based find and replace by detecting raw-string prefixes (`r"…"` or `r'…'`) and executing global RegExp matching with a hard cap at 500 matches to prevent runaway processing.**

The iOfficeAI/OfficeCLI repository provides a robust command-line interface for manipulating Office documents, with its **find and replace regex** capabilities implemented across both client-side JavaScript and server-side C# handlers. This dual-layer architecture ensures consistent pattern detection whether you're working through the browser overlay or directly via CLI commands.

## How OfficeCLI Detects Regex Patterns

OfficeCLI uses a strict raw-string convention to distinguish regex patterns from literal text. The system recognizes a pattern as a regular expression only when the find value is wrapped with `r"` or `r'` (for example, `r"\d{4}"`). This convention is enforced symmetrically on both the client and server to maintain protocol consistency.

### Client-Side Detection in watch-overlay.js

On the client side, the helper function `_isRegexFind` validates the regex format by checking that the find string starts with `r` followed by a matching quote and ends with the same quote. This logic appears in [`src/officecli/Resources/watch-overlay.js`](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/Resources/watch-overlay.js) at lines 301-306.

Once validated, `_extractRegexPattern` strips the prefix and suffix to return the raw pattern for execution (lines 308-311). If the pattern fails validation, the system automatically falls back to literal string matching.

### Server-Side Handling in WordHandler.Set.cs

The server-side implementation in [`src/officecli/Handlers/Word/WordHandler.Set.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/Handlers/Word/WordHandler.Set.cs) mirrors this behavior. When the `regex=true` property is supplied, the C# code automatically adds the `r"…"` wrapper around the find text unless it is already present (lines 307-313).

Both implementations share a `CONSISTENCY(find-regex)` comment (appearing in both the JavaScript and C# files) that documents this shared protocol, ensuring any changes to regex detection remain synchronized across the stack.

## Executing Regex Replacements in watch-overlay.js

When the overlay detects a regex pattern, it constructs a global `RegExp` object using `new RegExp(patt, 'g')` and iterates through the target element's text. This execution happens in [`src/officecli/Resources/watch-overlay.js`](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/Resources/watch-overlay.js) between lines 66-88 and 96-99.

### Global Matching and Safety Limits

The regex engine implements two critical safety mechanisms:

- **Zero-width protection**: The loop advances the cursor past matches of length 0 to prevent infinite loops on patterns like `\b` or `^`
- **Match capping**: Processing halts after 500 matches to protect against performance degradation on large documents or overly broad patterns

### Span Wrapping and Stale Mark Handling

For each successful match, the overlay creates a `<span>` wrapper that optionally carries:
- The replacement text (via the `replace` property)
- Color styling attributes
- A "stale" flag indicating orphaned marks

If a regex find yields no matches, the entire element receives the `.officecli-mark-stale` class, providing visual feedback that the pattern failed to locate target content.

## Literal String Fallback Behavior

When the find value lacks the `r"…"` prefix, OfficeCLI falls back to a simple `String.indexOf` search after normalizing Unicode to NFC form. This fallback is implemented in [`src/officecli/Resources/watch-overlay.js`](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/Resources/watch-overlay.js) at lines 100-112, ensuring consistent behavior with international characters while maintaining performance for basic text replacement.

## Practical Command Examples

Use these patterns to leverage OfficeCLI's regex capabilities in your workflow:

```bash

# Literal find (no regex)

officecli set --path /sheet1 --find "Invoice" --replace "Bill"

# Regex find using raw-string prefix

officecli set --path /sheet1 --find r"\d{4}-\d{2}-\d{2}" --replace "DATE"

# Explicit regex flag (server adds r"…" wrapper automatically)

officecli set --path /sheet1 --find "^\d{5}$" --replace "ZIP" --prop regex=true

```

Under the hood, the CLI transmits the `find` and optional `replace` values to the server, where `WordHandler.Set` processes the `regex` property, normalizes the pattern format, and dispatches the command to the browser overlay for execution.

## Summary

- **Pattern Detection**: OfficeCLI recognizes regex via `r"…"` or `r'…'` prefixes, validated by `_isRegexFind` in [`watch-overlay.js`](https://github.com/iOfficeAI/OfficeCLI/blob/main/watch-overlay.js)
- **Server Integration**: [`WordHandler.Set.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/WordHandler.Set.cs) automatically wraps patterns when `regex=true` is specified, maintaining the `CONSISTENCY(find-regex)` protocol
- **Safety Mechanisms**: Global regex execution caps at 500 matches and protects against zero-width infinite loops
- **Visual Feedback**: Failed matches trigger the `.officecli-mark-stale` class for immediate UI indication
- **Unicode Support**: Literal searches normalize text to NFC before matching, ensuring consistent behavior across international character sets

## Frequently Asked Questions

### How does OfficeCLI distinguish between regex and literal text?

OfficeCLI requires regex patterns to use a raw-string prefix of either `r"` or `r'`. The client-side `_isRegexFind` function in [`src/officecli/Resources/watch-overlay.js`](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/Resources/watch-overlay.js) validates this format by checking that the string starts with `r` followed by a matching quote character and ends with the same quote. Without this prefix, the system treats the input as a literal string and uses `String.indexOf` instead.

### What happens if my regex pattern matches too many times?

The system implements a hard limit of 500 matches per operation to prevent performance degradation. In [`src/officecli/Resources/watch-overlay.js`](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/Resources/watch-overlay.js), the matching loop checks the iteration count and breaks after reaching this cap. This protects against runaway processing when using broad patterns like `.*` on large documents.

### Can I use the regex flag without manually typing the r" prefix?

Yes. When using the `--prop regex=true` flag in your CLI command, the server-side [`WordHandler.Set.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/WordHandler.Set.cs) automatically wraps your find text with the `r"…"` prefix before sending it to the client. This ensures consistency with the client-side detection logic while providing a more convenient interface for command-line users.

### Why does my regex match show as "stale" in the UI?

The `.officecli-mark-stale` class appears when a regex find operation yields zero matches. In [`src/officecli/Resources/watch-overlay.js`](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/Resources/watch-overlay.js), the overlay marks the entire element as stale when the `RegExp` execution returns no results, providing visual feedback that the pattern did not locate the intended target text. This helps identify orphaned marks or incorrect regex syntax immediately.