> ## Documentation Index
> Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
> Use this file to discover all available pages before exploring further.

# TypeScript RegExp

A `RegExp` in TypeScript is an object representing a regular expression, utilized for pattern matching and text manipulation within strings. TypeScript provides static typing over the native JavaScript `RegExp` implementation through built-in interfaces such as `RegExp`, `RegExpMatchArray`, and `RegExpExecArray`, ensuring type safety when interacting with match results, indices, and capture groups.

## Instantiation

Regular expressions in TypeScript can be instantiated using either literal syntax or the `RegExp` constructor. The literal syntax is compiled when the script is loaded, whereas the constructor is compiled at runtime.

```typescript theme={"dark"}
// Literal syntax
const literalRegex: RegExp = /^[a-z]+$/i;

// Constructor syntax
const constructorRegex: RegExp = new RegExp('^[a-z]+$', 'i');

// Constructor with dynamic string
const dynamicPattern: string = "^[a-z]+$";
const dynamicRegex: RegExp = new RegExp(dynamicPattern, 'i');
```

## TypeScript Core Interfaces

TypeScript defines specific return types for regular expression operations to handle the complex arrays returned by the underlying JavaScript engine.

* **`RegExp`**: The interface representing the regular expression instance.
* **`RegExpExecArray`**: An array type returned by `RegExp.prototype.exec()`. It extends `Array<string>` and includes the required properties `index` (number) and `input` (string), alongside an optional `groups` property (`{ [key: string]: string } | undefined`) which is populated only when named capture groups are present.
* **`RegExpMatchArray`**: An array type returned by `String.prototype.match()`. It extends `Array<string>` but differs from `RegExpExecArray` by typing the `index` and `input` properties as optional (`index?: number`, `input?: string`). This distinction accounts for the runtime behavior where `match()` omits these properties when the global (`g`) flag is applied.

```typescript theme={"dark"}
const pattern: RegExp = /(?<vowel>[aeiou])/g;
const text: string = "hello";

// exec() returns RegExpExecArray | null
const execResult: RegExpExecArray | null = pattern.exec(text);

if (execResult !== null) {
    const fullMatch: string = execResult[0];        // "e"
    const capture: string = execResult[1];          // "e"
    const index: number = execResult.index;         // 1
    const input: string = execResult.input;         // "hello"
    
    // groups is typed as { [key: string]: string } | undefined
    const namedGroup: string | undefined = execResult.groups?.vowel; 
}
```

## RegExp Instance Methods

The `RegExp` object exposes two primary methods for pattern evaluation.

**`test()`**
Evaluates the string against the pattern and returns a boolean indicating whether a match exists.

```typescript theme={"dark"}
const regex: RegExp = /\d+/;
const isMatch: boolean = regex.test("TypeScript 5"); // true
```

**`exec()`**
Executes a search for a match in a specified string. Returns a `RegExpExecArray` if successful, or `null` if it fails. When the `g` (global) or `y` (sticky) flags are present, `exec()` updates the `lastIndex` property of the `RegExp` instance, allowing for stateful iteration.

```typescript theme={"dark"}
const globalRegex: RegExp = /[a-z]/g;
const str: string = "ab";

let match: RegExpExecArray | null;
while ((match = globalRegex.exec(str)) !== null) {
    console.log(`Found ${match[0]} at ${match.index}. Next start: ${globalRegex.lastIndex}`);
}
```

## String Methods Utilizing RegExp

TypeScript strongly types the `String` prototype methods that accept `RegExp` arguments.

```typescript theme={"dark"}
const target: string = "TS 5.0";
const regex: RegExp = /\d\.\d/;

// match: Returns RegExpMatchArray | null
const matched: RegExpMatchArray | null = target.match(regex);

// matchAll: Returns an IterableIterator of RegExpMatchArray. Requires 'g' flag.
const allMatches: IterableIterator<RegExpMatchArray> = target.matchAll(new RegExp(regex, 'g'));

// replace: Accepts RegExp and a replacement string or replacer function
const replacedStr: string = target.replace(regex, "X.X");
const replacedFn: string = target.replace(regex, (substring: string, ...args: any[]) => "X.X");

// search: Returns the index of the first match, or -1
const searchIndex: number = target.search(regex);

// split: Returns an array of strings split by the RegExp pattern
const splitArr: string[] = target.split(/\s+/);
```

## Flags and Modifiers

TypeScript supports standard ECMAScript regular expression flags. The presence of certain flags alters the expected return types or available properties.

* `g` (Global): Finds all matches rather than stopping after the first.
* `i` (Ignore case): Makes matches case-insensitive.
* `m` (Multiline): Changes behavior of `^` and `$` to match the start/end of lines.
* `s` (DotAll): Allows `.` to match newline characters.
* `u` (Unicode): Treats patterns as sequences of Unicode code points.
* `y` (Sticky): Matches only from the index indicated by the `lastIndex` property.
* `d` (HasIndices): Generates match indices.

**The `d` Flag (Indices)**
When the `d` flag is utilized, TypeScript recognizes the `indices` property on the resulting `RegExpExecArray`. This requires the `es2022.regexp` library in the `tsconfig.json`.

```typescript theme={"dark"}
const indicesRegex: RegExp = /foo/d;
const result: RegExpExecArray | null = indicesRegex.exec("foo bar");

if (result && result.indices) {
    // indices is typed as [number, number][]
    const [start, end] = result.indices[0]; 
}
```

<div
  style={{ 
display: "flex", 
justifyContent: "space-between", 
alignItems: "center", 
maxWidth: "754px", 
padding: "1rem 0",
marginBottom: "24px"
}}
>
  <span style={{ fontWeight: "bold", fontSize: "1.25rem", color: "var(--tw-prose-headings)", fontFamily: "Inter, ui-sans-serif, system-ui, sans-serif" }}>Tired of Poor TypeScript Skills? Fix That With Deep Grasping!</span>

  <a
    href="https://syntblaze.com"
    target="_blank"
    style={{ 
  marginLeft: "24px",
  textDecoration: "none", 
  backgroundColor: "#007AFF",
  color: "#ffffff", 
  padding: "6px 16px", 
  borderRadius: "16px",
  fontSize: "0.9rem",
  fontWeight: "600",
  textAlign: "center",
  transition: "background-color 0.2s ease"
}}
  >
    Learn More
  </a>
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/skill-tracking.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=b9b0305c93bb501c9e767b5c76c88835" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/skill-tracking.png" />

  <img src="https://mintcdn.com/syntblazellc/23tyuOzaWS88qFlc/images/nuggets.png?fit=max&auto=format&n=23tyuOzaWS88qFlc&q=85&s=c86c80197299762989e9b882419b2109" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/nuggets.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/bite-sized-exercises.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=a65f9a38c37ff28ab73ed783c53c60e3" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/bite-sized-exercises.png" />
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap", marginTop: "12px" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/mastery-chain.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=748a1763454713e679260fbb95f154a2" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/mastery-chain.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-previews.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=242f61448ff5dd6deaaab2dccc13b507" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-previews.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-explanations.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=cf0fc1c31f9cd0fc26716781be05fbc9" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-explanations.png" />
</div>
