---
title: regexp_replace function
description: Learn the syntax of the regexp\_replace function of the SQL language in Databricks SQL and Databricks Runtime.
canonical_url: https://docs.databricks.com/aws/en/sql/language-manual/functions/regexp_replace
---

# `regexp_replace` function

**Applies to:** ![check marked yes](https://docs.databricks.com/aws/en/images/icons/check.png) Databricks SQL ![check marked yes](https://docs.databricks.com/aws/en/images/icons/check.png) Databricks Runtime

Replaces all substrings of `str` that match `regexp` with `rep`.

## Syntax

```
regexp_replace(str, regexp, rep [, position] )
```

## Arguments

* `str`: A `STRING` expression to be matched.
* `regexp`: A `STRING` expression with a matching pattern.
* `rep`: A `STRING` expression which is the replacement string.
* `position`: A optional integral numeric literal greater than 0, stating where to start matching. The default is 1.

## Returns

A `STRING`.

The `regexp` string must be a regular expression. See [Regular expressions](https://docs.databricks.com/aws/en/sql/language-manual/sql-ref-regexp-pattern.md) for the supported syntax.

When using literals, use [`raw-literal` (`r` prefix)](https://docs.databricks.com/aws/en/sql/language-manual/data-types/string-type.md) to avoid escape character pre-processing.

Searching starts at `position`. The default is 1, which marks the beginning of `str`.
If `position` exceeds the character length of `str`, the result is `str`.

## Common error conditions

* [INVALID\_PARAMETER\_VALUE.PATTERN](https://docs.databricks.com/aws/en/error-messages/invalid-parameter-value-error-class.md#pattern)
* [INVALID\_REGEXP\_REPLACE](https://docs.databricks.com/aws/en/error-messages/error-classes.md#invalid_regexp_replace)

## Examples

### Replace every match with fixed text

```sql
> SELECT regexp_replace('100-200', r'(\d+)', 'num');
 num-num
```

### Mask digits

```sql
> SELECT regexp_replace('SSN 123-45-6789', r'\d', '#');
 SSN ###-##-####
```

### Reorder parts using capture groups

In the replacement string, use `$` followed by the group number to refer to a capture group (`$1`, `$2`).

```sql
> SELECT regexp_replace('2024-03-15', r'(\d{4})-(\d{2})-(\d{2})', '$3/$2/$1');
 15/03/2024
```

### Collapse repeated whitespace

```sql
> SELECT regexp_replace('too    many   spaces', r'\s+', ' ');
 too many spaces
```

### Invalid regex pattern

```sql
> SELECT regexp_replace('abc', '[invalid', 'x');
  Error: INVALID_PARAMETER_VALUE.PATTERN
```

## Related functions

* [Regular expressions](https://docs.databricks.com/aws/en/sql/language-manual/sql-ref-regexp-pattern.md)
* [`like` operator](https://docs.databricks.com/aws/en/sql/language-manual/functions/like.md)
* [`regexp_extract` function](https://docs.databricks.com/aws/en/sql/language-manual/functions/regexp_extract.md)
* [`regexp_extract_all` function](https://docs.databricks.com/aws/en/sql/language-manual/functions/regexp_extract_all.md)
