# Regular expressions

> Match text, inspect positions, scan repeated matches, and substitute using cached regex literals.

Canonical: https://alice-lang.org/documentation/library/regex/

[Documentation index](https://alice-lang.org/documentation/llms.txt) · [Complete book](https://alice-lang.org/llms-full.txt)

## Match a pattern

```alice
puts "rabbit42".match?(/\d+/) # true
puts "ALICE".match?(/alice/i) # true
```

A regex literal uses `/pattern/`. Alice caches literal regex instances. The regex engine and pattern semantics come from .NET.

## Select a result

| Form                                | Result                  |
| ----------------------------------- | ----------------------- |
| `text.match?(/pattern/)`            | Boolean match test      |
| `text =~ /pattern/`                 | Match position or `nil` |
| `text !~ /pattern/`                 | Nonmatch test           |
| `text.scan(/pattern/)`              | Repeated matching data  |
| `text.sub(/pattern/, replacement)`  | Replace the first match |
| `text.gsub(/pattern/, replacement)` | Replace all matches     |

A position result can be absent; check for nil before treating it as an index. Use `System.Text.RegularExpressions.Regex` directly when you need richer match/group APIs, explicit timeouts, or options beyond the literal form.

## Flags

| Flag | Meaning                   |
| ---- | ------------------------- |
| `i`  | Ignore case               |
| `m`  | Multiline anchors         |
| `x`  | Ignore pattern whitespace |
| `s`  | Singleline dot matching   |

The flags can be combined. Keep escaping clear: regex literal escapes describe a regex, while a .NET regex constructed from a string also goes through string escaping.

## Literal or regex?

Use `includes?`, `starts_with?`, `split`, or literal string replacement for a simple substring task. Use a regex for patterns. If patterns or inputs are untrusted and potentially expensive, use the .NET regex API's timeout support.

## Continue reading

- Previous: [Numbers, ranges, and math](https://alice-lang.org/documentation/library/numbers.md)
- Next: [Console, files, JSON, and environment](https://alice-lang.org/documentation/library/io.md)
